Search code examples
databaselaravelscheduled-taskspipeline

Laravel perform scheduled job on database


This is somewhat a design question for my current laravel side project.

So currently I have a table that stores a status value in one column and the date when that status should be altered. No I want to alter that status value automatically when the date is stored is the current date. Since that table will gain more rows about time I have to perform that altering process in a repeating manner. As well as that I want to perform some constraint checks on the data as well.

Im sure laravel is capable of doing that, but how?


Solution

  • Laravel has commands and a scheduler, combining these two gives exactly what you want.

    Create your command in Console\Commands folder, with your desired logic. Your question is sparse, so most of it is pseudo logic and you can adjust it for your case.

    namespace App\Console\Commands;
    
    class StatusUpdater extends Command
    {
    
        protected $signature = 'update:status';
    
        protected $description = 'Update status on your model';
    
        public function handle()
        {
            $models = YourModel::whereDate('date', now())->get();
    
            $models->each(function (YourModel $model) {
                if ($model->status === 'wrong') {
                    $model->status = 'new';
                    $model->save();
                }
            });
        }
    }
    

    For this command to run daily, you can use the scheduler to schedule the given command. Go to Commands\Kernel.php where you will find a schedule() method.

    use App\Commands\StatusUpdater;
    use Illuminate\Console\Scheduling\Schedule;
    
        class Kernel extends ConsoleKernel
        {
            protected function schedule(Schedule $schedule)
            {
                $schedule->command(StatusUpdater::class)->daily();
            }
        }
    }
    

    For scheduling to work, you have to add the following command to cronjob on your server. Which is described in the Laravel documentation.

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