如何自动删除7天后创建的数据库记录?我是否必须放入 index.blade.php 之类的东西?也许是一些调度程序?
public function index()
{
$results = Test::orderBy('created_at', 'desc')->take(5)->get();
if (!Auth::user()->isAdmin()) {
$results = $results->where('user_id', '=', Auth::id());
}
return view('results.index', compact('results'));
}
最佳答案
你可以使用 Laravel 任务调度来做到这一点。
https://laravel.com/docs/5.6/scheduling
安排一个每周运行的删除帖子的任务。
任务在 App\Console\Kernel
类的 schedule
方法中定义。
在那里你可以定义一个闭包:
protected function schedule(Schedule $schedule)
{
$schedule->call(function () {
Test::where('updated_at', '<', Carbon::now()->subDays(7))->delete();
})->weekly();
}
.
然后您必须添加一个 cron 作业,每隔几分钟(或您希望的任何时间范围)运行一次以运行这些命令。
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
.
这将检查到期任务并相应地运行它们。
希望对您有所帮助。如果您有任何疑问,请随时提出。
关于php - Laravel 如何在创建 7 天后删除数据库记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51586439/