Search code examples
phplaravellaravel-5php-carbon

Make scheduler to delete notifications that are 15 days old from now in laravel?


So I have a notifications table which has a created_at field which I can use for deleting the notifications which are 15 days old from now.

My scheduler code:

$schedule->call(function () {

$now = \Carbon\Carbon::now();


DB::table('notifications')
             ->where($now->diffInDays('created_at'), '>', 15)
             ->delete();

    })->daily();
}

But this gives error:

DateTime::__construct(): Failed to parse time string (created_at) at position 0 (c): The timezone could not be foun
  d in the database

How should I solve this ? And is there any other way using only php ?


Solution

  • The error you are getting it's because you are trying to get difference between Carbon object and a string ('created_at'). You can fix this by changing where clause like this

    ->where('created_at', '<', $now->subDays(15))
    

    Or you can write raw query instead.