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.
Has shown in other answers, you can:
\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();
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With