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

旧时模样 提交于 2021-01-01 11:01:55

问题


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:


  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



来源:https://stackoverflow.com/questions/59155235/how-can-i-publish-a-blog-posts-in-the-future-on-a-specific-date-and-time-in-lara

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!