Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5: Global Auth $user variable in all controllers

In my BaseController I have this:

public function __construct()
{
    $user = Auth::user();
    View::share('user', $user);
}

I can access the $user array throughout all of my views but what if I want it to be a global variable available in all of my Controllers?

I have the following working code:

use Auth;
use DB;

class UsersController extends BaseController
{
   public function index()
   {
        $user = Auth::user();
        $users = DB::table('users')->where('user_id', $user->user_id)->get();
        return view('pages.users.index', compact('users');
    }
}

I want the $user variable available in all of my controllers and within all of the public functions within each on the controllers but I don't want to have to redeclare "use Auth;" and "$user = Auth::user();"

I tried adding it to a __construct in the BaseController but that didn't seem to work, Undefined $user variable error. Any thoughts? I know it's possible.

like image 261
Chad Priddle Avatar asked Jan 07 '23 11:01

Chad Priddle


2 Answers

Has shown in other answers, you can:

  • set it as a property of your base controller (I don't recommend this, it just adds clutter)
  • create a custom helper (see below)
  • just do \Auth::user()


Another technique, you can use auth() helper:

auth()->user()

It is even documented.


According to this PR, there is no plan to add an user() helper in Laravel.

If you consider it is worth adding this helper to your project, here is the code:

function user()
{
    // short and sweet
    return auth()->user();

    // alternative, saves one function call!!
    return app('Illuminate\Contracts\Auth\Guard')->user();
}
like image 100
Gras Double Avatar answered Jan 15 '23 00:01

Gras Double


I do not see why something like this would not work:

public function __construct()
{
    $this->user = \Auth::user();
    \View::share('user', $this->user);
}

This way it's available to all your views and as long as your controllers are extending BaseController, it's available in all your controllers as well with $this->user.

like image 30
user1669496 Avatar answered Jan 14 '23 23:01

user1669496