Home > front end >  Laravel delete record of table after the next day of expiry date?
Laravel delete record of table after the next day of expiry date?

Time:02-03

Coupon::where('expire_date','<',Carbon::tomorrow())->delete(); 
// OR
Coupon::where('expire_date','<',Carbon::yesterday())->delete(); 

CodePudding user response:

If you want to get all the coupons where the expiry date ( 1 day) is less than today, you can to it with a raw query.

It's your choice if you want to use Carbon::today() (time will always be 00:00:00) or Carbon::now() for this.

Coupon::where(DB::raw('expire_date   INTERVAL 1 DAY'), '<', Carbon::now())->delete();

You could also move this logic into a query scope in the Coupon model.

# Coupon.php

use Illuminate\Database\Eloquent\Builder;

public function scopeExpired(Builder $query)
{
    return $query->where(DB::raw('expire_date   INTERVAL 1 DAY'), '<', Carbon::now());
}
Coupon::expired()->delete();

If you want this to happen automatically, you will need to set it up in the Scheduler.

# app/Console/Kernel.php

protected function schedule(Schedule $schedule)
{
    $schedule->call(fn() => Coupon::expired()->delete())->daily();
}

For the scheduler to run on its own, you need to add the following entry to your server's crontabs

* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
  • Related