0
votes

I'm at the beginner level using the laravel PHP framework. I worked on a blog web application, but I want to do some upgrade.

One of the upgrades is to be able to schedule posts to be published in the future on a selected date and time. Like that of Facebook, or that of rainlab blog in October CMS.

I don't know how to go about this, I would really appreciate it if someone can help me out.

2
By adding a datepicker in your admin panel that can set the date it should be visible?Jerodev
@Jerodev thank you I will do that, but how will I go about the controller, and method?Ifeoluwa Adewunmi

2 Answers

5
votes

The easiest way to implement delayed posting is to add publish date column (e.g published_at) to posts table and retrieve posts where publish date < now.

Schema:

$table->timestamp('published_at');

Retrieve example:

$posts = Post
    ::where('published_at', '<', now())
    ->orderByDesc('published_at')
    ->paginate(50);
2
votes
  1. The firstly i will create in database column like posted_at and show,that columns will be helpful later.
  2. You should create command using

php make:command MyCommand

  1. Then in your app/console/command you will have your command

  2. In app/console/kernel in

protected variable $commands

register your command,put path

  1. Inside your command using Eloquent or Db query get all posts where show=0 and posted_at

    $now=date("Y-m-d");
    $data=DB::table('test')->where('show',0)->whereRaw("posted_at<$now")->get();
    
  2. Now you can use each loop and change show=1,something like that:

    $date->each(function ($item){
     DB::table('test')->where('id',$item->id)->update(['show'=>1]);
    });
    

Last job is put in kernel code which will be run after 1m,try this ->

$schedule->command('myCommand')->everyMinute();

EDIT: So i checked my code i put changes so your command more or less should looks like this :

 $now=date("Y-m-d");
 $data=DB::table('test')->where('show_',0)->whereRaw("date(posted_at)<='$now'")->get();
 $data->each(function ($item){
 DB::table('test')->where('id',$item->id)->update(['show_'=>1]);

Remember to put in header of your command this if you use DB

 Use DB;

if Eloquent this but you must change the DB to Model_name

use App\Name_model;

And that is Kernel.php

protected $commands = [
        'App\Console\Commands\MyCommand',
    ];

// and 

protected function schedule(Schedule $schedule)
    {
        $schedule->command('My:Command')->everyMinute();
    }

I check if after 1min records in my test database was change ,and show_=0 changed to show_=1 and that's all