Laravel delete all rows older than 30 days

You can delete all rows from table which are 30 days older from current date. You can use whereDate() and whereRaw() SQL query method to delete the records from table.

Answers 1
  • Laravel eloquent to delete 30 days older records from today's date

    //1. whereRaw() SQL Query:
    $users = \App\Models\User::whereRaw('DATEDIFF(NOW(), created_at) > 30')->delete();
    dd($users);
    
    //OR
    //2. whereDate() method
    $users = \App\Models\User::whereDate('created_at', '<=', now()->subDays(30))->delete();
    dd($users);
    
    0

    It will delete all the records which are 30 days older from today's date and return the number of records as output deleted from table. You can use any of them to get the 30 days older records from the particular table.

  • Back to code snippet queries related laravel