Laravel Auth::user() alternatives

How to get authenticated user instance in Laravel

Panjeh
2 min readSep 16, 2019

Getting Authenticated user in Laravel

  • Using Facade:
Auth::user(); 
or
\Auth::user(); // without need to use Auth namespace
  • Using helper function :
auth()->user();

Note: Both of the above options do query database on each request!

  • In case we have Route::post() in our routes, our controller seems something like this:

Then inside the store action we can get the authenticated user via $request instance like:

$request()->user();

Note: The request option does not run query on database on each request!

Checking logged in user:

if(Auth::check()){    //  user is logged in}

We usually use check method in middleware.

Before you continue with the rest of this tutorial, I would like to introduce two packages for Laravel that I have recently developed: Laravel Pay Pocket, a modern multi-wallet package, and Laravel Failed Jobs, a UI for the Laravel Failed Jobs Table. I hope they may be of help to you.

https://github.com/HPWebdeveloper/laravel-pay-pocket
https://github.com/HPWebdeveloper/laravel-failed-jobs

Getting Authenticated user id:

Auth::user()->getId();orAuth::id();

Simulating a login:

  • Inside a controller we can login a user with the user_id = $id
auth()->loginUsingId($id);
  • or
auth()->login($user, false);
\Auth::login($user, false);
\Auth::login($user, true);

Note: false as the second argument means don’t tick remember_me when login a $user.

Inside Laravel Core:

How laravel core fetch the authenticated user when using can method in Authorization:

This is in Illuminate\Auth\AuthManager here

another case is happening here

--

--

Panjeh
Panjeh

Written by Panjeh

Posting about Python and Laravel

No responses yet