laravel - 'Auth' is not working in cron schedule

Viewed 184

I have created a cron job in the 'commands' files. and I want to get the id of the user using Auth::user()->id but I am getting the error. Where am I missing?

My error:

Trying to get property 'id' of non-object

My controller

use Illuminate\Support\Facades\Auth;

protected $signature = 'orders:minute';

public function handle()
    {
        $id = Auth::user()->id;
    }

Kernel.php

protected function schedule(Schedule $schedule)
{
    $schedule->command('orders:minute')
    ->everyMinute();
}
4 Answers

You can't do that because a user doesn't run the scheduled command, so Auth::user() object will always be null.

To fix this, you can save User Id in Database and fetch the data on scheduled command execution.

You can't do that because a user doesn't run the cron scheduled.

For the use case you're showing you'd have to provide it yourself, for example as a command argument:

protected $signature = 'command:Orders {user_id : id of the recipient model}';

public function handle() {
      $user_id = $this->argument('user_id');
      $user = User::findOrFail($user_id);
      // other commands
}

So executing php artisan command:SendNotification 1 would act as if user 1 was authenticated.

Cron means to run something automatically. You can't do that because a user doesn't run the cron scheduled. You only get Auth::user()->id when the user login

Related