Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

baskarks's avatar

How to delete data from DB automatically based on expiry date?

Can we use scheduler?. If yes then how.... Any example link

0 likes
1 reply
LaryAI's avatar
Level 58

Yes, you can use Laravel's scheduler to automatically delete data from the database based on an expiry date. Here's an example of how you can do it:

  1. Create a new console command using the make:command Artisan command:
php artisan make:command DeleteExpiredData
  1. Open the app/Console/Commands/DeleteExpiredData.php file and update the handle method to delete the expired data:
public function handle()
{
    DB::table('your_table')
        ->where('expiry_date', '<', now())
        ->delete();
}

Replace your_table with the name of your database table and expiry_date with the name of the column that contains the expiry date.

  1. Open the app/Console/Kernel.php file and add a new entry to the schedule method to run the command daily:
protected function schedule(Schedule $schedule)
{
    $schedule->command('delete:expired-data')->daily();
}

Replace delete:expired-data with the name of your console command.

  1. Save the files and run the following command to start the scheduler:
php artisan schedule:run

This will run the scheduler every minute and execute the DeleteExpiredData command once a day to delete the expired data.

Note: Make sure that your server's timezone is set correctly in the config/app.php file to ensure that the scheduler runs at the correct time.

1 like

Please or to participate in this conversation.