[英]How can I Publish A Blog Posts In The Future On A Specific Date And TIme In Laravel
我處於使用 laravel PHP 框架的初學者級別。 我開發了一個博客網絡應用程序,但我想做一些升級。
其中一項升級是能夠安排將來在選定的日期和時間發布帖子。 就像 Facebook 的那樣,或者 10 月 CMS 中的rainlab 博客的那樣。
我不知道該怎么做,如果有人可以幫助我,我將不勝感激。
實現延遲發布的最簡單方法是將發布日期列(例如已發布的_at)添加到帖子表並檢索發布日期 < 現在的帖子。
架構:
$table->timestamp('published_at');
檢索示例:
$posts = Post
::where('published_at', '<', now())
->orderByDesc('published_at')
->paginate(50);
php make:command MyCommand
然后在您的應用程序/控制台/命令中,您將擁有您的命令
在應用程序/控制台/內核中
受保護的變量 $commands
注冊您的命令,輸入路徑
在使用 Eloquent 或 Db 查詢的命令中,獲取 show=0 和 posts_at 的所有帖子
$now=date("Ymd"); $data=DB::table('test')->where('show',0)->whereRaw("posted_at<$now")->get();
現在您可以使用每個循環並更改 show=1,如下所示:
$date->each(function ($item){ DB::table('test')->where('id',$item->id)->update(['show'=>1]); });
最后一個工作放在內核代碼中,它將在 1m 后運行,試試這個 ->
$schedule->command('myCommand')->everyMinute();
編輯:所以我檢查了我的代碼並進行了更改,因此您的命令或多或少應該如下所示:
$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]);
如果您使用 DB,請記住在命令的標題中放入
Use DB;
如果 Eloquent this 但您必須將 DB 更改為 Model_name
use App\Name_model;
這就是 Kernel.php
protected $commands = [
'App\Console\Commands\MyCommand',
];
// and
protected function schedule(Schedule $schedule)
{
$schedule->command('My:Command')->everyMinute();
}
我檢查我的測試數據庫中的記錄是否在 1 分鍾后更改,並且 show_=0 更改為 show_=1,僅此而已
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.