Laravel automatically change status in database after date expires
P粉447002127
P粉447002127 2023-12-15 13:36:40
0
3
475

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粉447002127
P粉447002127

reply all(3)
P粉683665106

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.

P粉092778585

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','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
似水

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

606915a3b01db9aab05d290248494e3.jpg

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!