How to store records on the end of the day in laravel

Viewed 510

For example, If user forgot to approve till the end of the day a message will store to the database at the end of the day. I used the carbon format as below.

if (Carbon::now()->endOfDay()->eq(Carbon::parse($phaseValue->end_date)->endOfDay())) {
// add records here
}
2 Answers

You will have to set up a task scheduler that will check if a specific condition has been met at the end of the day. if not then it will do the insertion in DB or anything according to your business logic. Laravel provides task scheduling, have a look:

https://laravel.com/docs/8.x/scheduling

You could create a cron job that would run every day at the given time. To do that, create a new command:

php artisan make:command YourCommand

Then, your command would look something like this:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class YourCommand extends Command
{
    //Name that will be used to call command
    protected $signature = 'your:command';

    protected $description = 'Command description';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        //Here you will handle all the logic. For ex:
        $record = App/Example::first();
        
        //Implement condition that will determine if the record will be updated
        $record->update();
    }
}

After that, inside App/Console/Kernel.php create the schedule for that command:

protected function schedule(Schedule $schedule)
{
    //Name that you gave it in the protected $signature = 'your:command';
    $schedule->command('your:command')->dailyAt('23:30');
}

This way the command will be run every day at 23:30 and you can update your records any way you want. You can read more about task scheduling & commands on the official docs.

Related