Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete Elequent records older than 60 minutes

How can I delete all Eloquent Records in a database where the created_at or updated_at field is older than 60 minutes? (or any amount of time for the example)

edit: posted solution as answer as @Alexxus suggested

like image 524
Barry127 Avatar asked Feb 12 '23 17:02

Barry127


2 Answers

Laravel have a build in Carbon date class which handles all the timezone problems for you.

Example:

$date  = Carbon::now()->subMinutes( 60 );
MyModel::where( 'updated_at', '<=', $date )->delete();
like image 157
Mike Aron Avatar answered Feb 15 '23 11:02

Mike Aron


Solved -> With ceejayoz his link

  • Make a date object and minus the amount of time.
  • Covert the date object to string to match Eloquent formatting
  • Compare formatted string against updated_at

I'm using the following code:

$date = new DateTime;
$date->modify('-60 minutes');
$formatted = $date->format('Y-m-d H:i:s');
MyModel::where('updated_at', '<=', $formatted)->delete();

Thanks ceejayoz!

like image 35
Barry127 Avatar answered Feb 15 '23 09:02

Barry127