Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

If I want to check whether the user is logged in within my Laravel 5.1 application I can either use

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

or

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

is there a reason to prefer one over the other when checking if a user is logged in?

like image 908
tam5 Avatar asked Nov 02 '15 17:11

tam5


People also ask

Which is best authentication for Laravel?

By default, Laravel includes an App\User Eloquent model in your app directory. This model may be used with the default Eloquent authentication driver. If your application is not using Eloquent, you may use the database authentication driver which uses the Laravel query builder.

What is auth ()- user () in Laravel?

Auth::user() — You can check if a user is authenticated or not via this method from the Auth Facade. It returns true if a user is logged-in and false if a user is not. Check here for more about how Facades work in Laravel.

What is Auth :: Routes () in Laravel?

Auth::routes() is just a helper class that helps you generate all the routes required for user authentication. You can browse the code here https://github.com/laravel/framework/blob/5.3/src/Illuminate/Routing/Router.php instead.


3 Answers

Auth::check() defers to Auth::user(). It's been that way since as long as I can remember.

In other words, Auth::check() calls Auth::user(), gets the result from it, and then checks to see 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 if it's null, and then returns a boolean value.

like image 145
Thomas Kim Avatar answered Sep 28 '22 13:09

Thomas Kim


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

Auth::user() will make a database call (and be slightly heavier) than Auth::check(), which should simply check the session.

like image 37
samlev Avatar answered Sep 28 '22 13:09

samlev


I recomend you to define $user = auth()->user(); If you want to check if user is authenticated or not and user model properties like email, name, ... in your code.

Because auth()->user() and auth()->check() both will query to database. If you want more speed in your apps, define $user = auth()->user(); then you can us it in your codes and also you can check if user is authenticated via $user == null;.

Don't use auth()->check() and auth()->user() both in one function or one block of code to have low queries to database and more speed apps! ; )