1
0

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のViewに共通変数でAuthの情報をセットする

Posted at

概要

ログイン後のContollerで毎回AuthのチェックをしてDB取得してwithの変数にいれるのが大変なのでググってコピペで入れたら失敗して修正した件。

AppServiceProviderでは処理の順でAuthのcheck()が効かないので、callback式に書いておくと、あとで処理してくれる。

もっと簡潔な方法はありそう。

環境

php:8.1
Laravel:8.8

コード

AppServiceProvider

    // ここに書く
    public function boot(UrlGenerator $url){

        // viewのcallback処理追加
        view()->composer('*', function ($view) {

            // ログインしていれば
            if(\Auth::guard('admin')->check()) {

                              // ログインユーザの情報を常にセット
                $admin_user = AdminUser::where('id',\Auth::guard('admin')->id())->first();
                view()->share('admin_user', $admin_user);
            }
        });


    }

参考

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?