0
0

More than 1 year has passed since last update.

【Laravel】通常の実行で正常に動作する処理がコマンド実行ではエラーになる原因がAuthファサードだった!

Last updated at Posted at 2023-02-08

通常の実行(ボタンを押すと発火する処理等)では、上手くいくのに、ターミナルでのコマンド実行(php artisan batch:Test)や、自動実行(php artisan schedule:run)で実行した場合にエラーになりました。

原因はauthファサードだったので、備忘録を兼ねて記事にしました。

考察

authファサードはログインした状態のユーザーが実行した場合に使えるメソッドです。

今回、私が実行したコマンド処理がcronで自動実行する処理だったため、ログインしていない状態で実行していました。

そのため、authファサードを実行しても空が返ってきたようです。

開発時にログインした状態でボタン発火を行い検証していたため、同じ処理でもコマンド時に上手くいかなかったようです。

ボタン発火の処理であれば、laravelのdd機能が使えて楽に開発できるのですが、こういった点に目を落とすため注意が必要ですね。

次に検証の際に実行した処理を記載します。

実行処理

TestCommand.php
class TestCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'batch:Test';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'テスト';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        Log::debug(Auth::id());
        Log::debug(auth()->id());
        return 0;
    }
}

コマンド

ターミナル
php artisan batch:Test

ログ

空で出力される

laravel.log
[2023-02-09 03:44:39] local.DEBUG:   
[2023-02-09 03:44:39] local.DEBUG:   

環境

Windows 10
PHP 7.4.29
Laravel Framework 8.83.15

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0