简体   繁体   中英

How can I Publish A Blog Posts In The Future On A Specific Date And TIme In Laravel

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.

The easiest way to implement delayed posting is to add publish date column (eg 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);
  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("Ymd"); $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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM