5

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

Barry127
  • 1,212
  • 1
  • 12
  • 23
  • 2
    possible duplicate of [Laravel select records older than 5 minutes?](http://stackoverflow.com/questions/19475896/laravel-select-records-older-than-5-minutes) – ceejayoz Jun 16 '14 at 18:38
  • I would start by learning the MySQL date/time functions http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timediff. – Dave Jun 16 '14 at 18:48
  • Please post the aswer as answer – Alexxus Oct 30 '18 at 06:16

2 Answers2

7

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();
Mike Aron
  • 550
  • 5
  • 13
4

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!

Barry127
  • 1,212
  • 1
  • 12
  • 23