Home > OS >  Delete Rows Older than 30 Days Using Laravel Eloquent ORM
Delete Rows Older than 30 Days Using Laravel Eloquent ORM

Time:10-06

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?

CodePudding user response:

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!

CodePudding user response:

  1. You have a typo. Try

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

  1. It would run gracefully
  • Related