laravellaravel-bladelaravel-7user-variables

How to populate variable to all view logged user


I have code like bellow:

return view('Dashboard.AccountSettingsView', [
    'PageTitle' => config('app.name', 'Laravel') . ' | ' . __('Profile'),
    'PageHeader' => __('Profile'),
    'user' => Auth::user()
]);

How i can pass $user variable to all login user view, so i don't need to create 'user' => Auth::user() in every controller.

Thank you


Solution

  • Yes it's easy, what you can do is that add * for all the views. And add a check in case there is no login user.

        public function boot()
        {
            View::composer('*', function ($view) {
               if (Auth::check()) {
                $view->with('user', Auth::user());
                 }
            });
        }