4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Laravel】Controllerのコンストラクタではuserが取れない

Posted at

ユーザーが取れない!

HogeController.php
public function __construct()
{
    $user = Auth::user(); // $userがnull
}

コントローラのコンストラクタでユーザーを取ってこようとするとnullが帰ってきます。これはmiddlewareをまだ通っていないからだそうです。

これを回避するにはコントローラミドルウェアを使うと回避可能です。

NewHogeController.php
public function __construct()
{
    $this->middleware(function ($request, $next) {
        $user = Auth::user();
        // ここに$userに関する処理を書く
        return $next($request);
    });
}

参考

4
3
1

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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?