What to use Auth :: check () or Auth :: user () - Laravel 5.1?

If I want to check if a user is registered in my Laravel 5.1 application, I can either use

if (Auth::user()) {...} 

or

 if (Auth::check()) {...} 

Is there a reason to prefer each other when checking if a user is registered?

+7
source share
4 answers

No, the accepted answer is incorrect.

Auth::check() cancels Auth::user() . That was as long as I remember.

In other words, Auth::check() calls Auth::user() , gets the result from it, and then checks if the user exists. The main difference is that it checks if the user is null for you so that you get a boolean value.

This is the check function:

 public function check() { return ! is_null($this->user()); } 

As you can see, it calls the user() method, checks to see if it is null, and then returns a boolean.

+8
source

If you just want to check if the user is logged in, Auth::check() more accurate.

Auth::user() will make the database call (and be a little harder) than Auth::check() , which should just check the session.

+3
source

I recommend you define $user = auth()->user(); If you want to check whether the user is authorized or not, and specify properties of the user model in your program, such as email, name, ....

Because auth()->user() and auth()->check() will execute database queries. If you want more speed in your applications, define $user = auth()->user(); then you can use it in your codes, and you can also check if the user has authenticated through $user == null; ,

Do not use auth()->check() and auth()->user() both in one function and in one block of code to have low database queries and faster applications! ; )

0
source
 Auth::guard('admin')->user()->email 

try it, it worked for me.

-1
source

All Articles