Search code examples
phplaravellaravel-8query-builderlaravel-scheduler

Laravel 8 Task scheduler


I'm using laravel Scheduler, i want to set a subscription status to expired if a certain condition is met, and also need this to run every mins in the background..Figured task scheduler is the best option but couldn't figure out why the code is'nt executing after running php artisan schedule:work ..Below is my code Located in App/Console/Kernel.php (schedule function)

  $schedule->call(function () {
        $checkSubStatus = UserSubscription::where('status', 'approved')->where('users_id', auth()->user()->id)->first();
        $currentTime = Carbon::now();
        if($currentTime > $checkSubStatus->expiry_date) {
            $checkSubStatus->update([
                'status' => 'expired'
            ]);
        }
    })->everyMinute();

But works when i just delete the table, like so DB::table('users_subscription')->delete(); Please any help?


Solution

  • You have an exception caused by auth()->user()->id, since no user is logged when your closure is executed.

    You can check the logs in storage/logs/laravel.log and if it is the case, the solution is just to avoid using any authentification mechanisms inside the scheduler.

    As an alternative, you have to rethink what UserSubscription should be expired:

    UserSubscription::where('status', 'approved')
    ->where('expiry_date', '<', now())
    ->update(['status' => 'updated');
    

    No user anymore, you just expire every subscriptions where the date is before now.

    Credit to Emre Kaya for finding the error.