问题
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.
回答1:
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:
- The firstly i will create in database column like posted_at and show,that columns will be helpful later.
- You should create command using
php make:command MyCommand
Then in your app/console/command you will have your command
In app/console/kernel in
protected variable $commands
register your command,put path
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();
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
来源:https://stackoverflow.com/questions/59155235/how-can-i-publish-a-blog-posts-in-the-future-on-a-specific-date-and-time-in-lara