0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Laravel7|1分ごとに古いデータを削除するスケジュール

Posted at

投稿する記事が毎日数件ある状況。

このままだと増えていく一方。

古いデータはもういらないから、それを定期的に削除するスケジューラーを作ってみた。

1.コマンドファイル作成
2.カーネルファイル修正
3.クーロンタブ修正

この手順で解説

1.コマンドファイル作成

まずはコマンド実行ファイルの作成

$php artisan make:command delOldPost

\App\Console\Commandsに
delOldPost.phpができるので修正

コマンド名をつけてやりたい処理を描かく

delOldPost.php
protected $signature = 'command:deloldpost';//コマンド名

public function handle()
    {
       //処理内容(一番古いものを削除する)
       $post=Post::oldest()->first()->delete();
    }

手動実行してみる

$php artisan command:deloldpost

ちゃんとデータが消えていればOK

2.カーネルファイル修正

\App\Console\Kernelファイル修正

動かすコマンドファイルを指定

Kernel.php
protected $commands =
   \App\Console\Commands\delOldPost::class
];

protected function schedule(Schedule $schedule)
{
    //コマンド名と実行タイミング
    $schedule->command('command:deloldpost')->everyMinute();
}

3.クーロンタブ修正

cronrab -e
* * * * * cd アプリまでのパス && php artisan schedule:run >> /dev/null 2>&1

:wで保存
:qで抜ける
crontab -lで確認

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?