Home > Software design >  Laravel automatically change status in DB after date expires
Laravel automatically change status in DB after date expires

Time:06-24

I've got the tasks table, this table has status and deadline columns. How can status be changed to "expired" automatically when current date will become greater than task's deadline date? Is there any realtime event listeners in Laravel?

I guess that's how event listener class should look like, but I'm not sure what to do next.

<?php
 
namespace App\Events;
 
use App\Models\Task;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
 
class DeadlineExpired
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
 
    /**
     * The task instance.
     *
     * @var \App\Models\Task
     */

    public $task;
 
    /**
     * Create a new event instance.
     *
     * @param  \App\Models\Task $task
     * @return void
     */
    public function __construct(Task $task)
    {
        $this->task = $task;
    }
}

CodePudding user response:

There are Realtime event listeners but thes require a action to fire. Example are when a model is Created, Updated or Deleted then these events fire.

There is no built in "listener" to ping every model waiting for a field you defined to change.

If there is further logic you would like to fire when the Task becomes expired (like send email) then your best would be to run a check for any new expired Tasks using the scheduler. The Scheduler runs every minute - set by cron.

CodePudding user response:

Since you're checking only the date. Your cron needs to run only once at midnight. Use Laravel Scheduler to do your Job. First create a class

class UpdateTasks
{
    public function __invoke()
    {
        // do your task here...e.g.,
        Tasks::whereDate('deadline','<',today())->update(['status'=>'expired']);
    }
}

Then in your app\Console\Kernel.php, schedule method-

$schedule->call(new UpdateTasks())->daily();

Finally configure a cron job at your server to run the schedule command daily at midnight.

php artisan schedule:run
  • Related