Home  >  Q&A  >  body text

Laravel automatically change status in database after date expires

I have tasks table which has status and deadline columns. How to automatically change the status to "Expired" when the current date is greater than the task due date? Are there real-time event listeners in Laravel?

I think this is what the event listener class should look like, but I'm not sure what to do next.

<?php
 
namespace AppEvents;
 
use AppModelsTask;
use IlluminateBroadcastingInteractsWithSockets;
use IlluminateFoundationEventsDispatchable;
use IlluminateQueueSerializesModels;
 
class DeadlineExpired
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
 
    /**
     * The task instance.
     *
     * @var AppModelsTask
     */

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


P粉447002127P粉447002127332 days ago529

reply all(3)I'll reply

  • P粉683665106

    P粉6836651062023-12-16 11:39:22

    There is a real-time event listener, but it needs to perform an operation to trigger. For example, these events are triggered when a model is created, updated, or deleted.

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

    If you want to trigger further logic (such as sending an email) when a task expires, then you'd better use a scheduler to check if there are any new overdue tasks. Scheduler runs every minute - set by cron.

    reply
    0
  • P粉092778585

    P粉0927785852023-12-16 10:27:05

    Because you are only checking the date. Your cron only needs to run once at midnight. Use Laravel Scheduler to get your work done. 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 on your server to run the scheduled command every day at midnight.

    php artisan schedule:run

    reply
    0
  • 似水

    似水2023-12-16 15:18:34

    I will use GPT to help you answer your question. I hope it will be useful

    606915a3b01db9aab05d290248494e3.jpg

    reply
    0
  • Cancelreply