'Delete Rows Older than 30 Days Using Laravel Eloquent ORM

I'm trying to delete the records from my database table that are older than 30 days. I haven't executed the code because I wanted to check if I'm doing it right.

App\MyTable::whereDate( 'created_at', '<=', now()->subDays( 30 ) )->delete();

Is that a correct way of deleting rows older than 30 days from a table? Also, what would happen if it found zero records older than 30 days, would it throw an exception error or just run gracefully?



Solution 1:[1]

  1. You have a typo. Try

MyTable::whereDate( 'created_at', '<=', now()->subDays(30))->delete();

  1. It would run gracefully

Solution 2:[2]

Try this -

$from= Carbon::now()->subDays(30)->toDateString();

$current = Carbon::now()->toDateString();

ModelName::whereBetween('created_at', array($diff,$current))
           ->delete();

Hope this works perfectly! Please also let me know it works or not!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Zachary Craig
Solution 2 Mohaimen Khalid