Reputation: 3584
When I click on save button, it collects the task details(name, message, the lapse period), and then it calculates the expiry date from the current date it was posted.
public function store(Request $request)
{
$currentDate = date("m-d-Y H:i:s");
$currentDate_timestamp = strtotime($currentDate);
$endDate_months = strtotime($request->lapse_period, $currentDate_timestamp);
$packageEndDate = date("m-d-Y H:i:s", $endDate_months);
echo " <br> " . $packageEndDate . " <br> ";
Task::create([
'name' => $request->name,
'message' => $request->message,
'lapse_period' => $request->lapse_period,
'expires_at' => $packageEndDate
]);
return redirect()->back();
}
That works, and the question is: How can I create a task that runs every minute and deletes all records that expiry date lesser than the current date?
This is what I tried in the Kernel but nothing happens after a minute:
protected function schedule(Schedule $schedule)
{
$schedule->call(function () {
$currentDate = date("m-d-Y H:i:s");
$tasks = Task::all();
foreach ($tasks as $task) {
if($date->expires_at < $currentDate) {
$task->delete();
}
}
})->everyMinute();
}
Upvotes: 0
Views: 1737
Reputation: 1593
Try the code below:
protected function schedule(Schedule $schedule)
{
$schedule->call(function () {
Task::where('expires_at','<', Carbon::now())->delete();
})->everyMinute();
}
Upvotes: 2
Reputation: 461
try this
protected function schedule(Schedule $schedule)
{
$schedule->call(function () {
$currentDate = \Carbon\Carbon::now();
$tasks = Task::all();
foreach ($tasks as $task) {
$dateTask = new \Carbon\Carbon($task->expires_at);
if($dateTask < $currentDate) {
$task->delete();
}
}
})->everyMinute();
}
Upvotes: 0