0

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

hrace009
  • 37
  • 9

1 Answers1

1

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());
             }
        });
    }
Andy Song
  • 4,404
  • 1
  • 11
  • 29
  • if use `Auth:check()`, it will show error $user is undefined – hrace009 Apr 13 '20 at 05:04
  • @IHarrisMarfel in you blade file? – Andy Song Apr 13 '20 at 05:06
  • @IHarrisMarfel you need to do some check anyways, otherwise the the `$user` will be null. and when you access the some properties in you blade you will get an error as well. – Andy Song Apr 13 '20 at 05:10
  • `if (Auth::check()) { View::composer('*', function ($view) { $view->with('user', Auth::user()); });` show undifine, but with `View::composer('*', function ($view) { if ( Auth::check() ){ $view->with('user', Auth::user()); } });` it run perfect – hrace009 Apr 13 '20 at 05:26