Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.2 Auth facade and Auth::guard($guard)

I am new to Laravel. I was browsing the default authenticate middleware and I see that it is using:

Auth::guard($guard)->guest()

to check if the user is a guest.

The documentation at https://laravel.com/docs/5.2/authentication#retrieving-the-authenticated-user tells that one can use:

Auth::check()

To figure out if a user is authenticated. (I image this is opposite of guest() ?

I tried changing the default code to use

Auth::guest()

and I am getting exactly the same result.

My question is, what is the difference between having guard($guard)-> or not in this case?

A related question. Is guest() completely opposite of check() or are there circumstances where these may return same results?

Thanks!

like image 374
Evren Yurtesen Avatar asked May 11 '16 19:05

Evren Yurtesen


2 Answers

The authenticate middleware allows you to specify what type of auth guard you want to use. Laravel 5.2 comes with two out of the box, 'web' and 'api'.

The Auth facade uses the 'web' guard by default if none is specified. So for example: Auth::user() is doing this by default: Auth::guard('web')->user()

The other auth driver out of the box called 'api'. So for example you can call your middleware like this: $this->middleware('auth:api');

This will check that the user is authenticated by api_token instead of session. Then you can get an instance of the user by Auth::guard('api')->user() instead of Auth::user() which is the same as Auth::guard('web')->user()

You would use this if your application has an API endpoint allowed for logged in users only. then a user can make a request like yourapp.com/api-method?api_token=blahblah. Then you can use the 'api' auth guard to authenticate and grab the logged in User.

I found this tutorial pretty useful in setting it up: http://learninglaravel.net/multiple-authentication-guard-drivers-including-api-in-laravel-52

And to answer your second question. Yes guest() is just the opposite of check(). check out laravel\framework\src\Illuminate\Auth\GuardHelpers.php

like image 130
Wesley Agena Avatar answered Oct 10 '22 12:10

Wesley Agena


Well there is no difference - if you examine the Auth facade than you'll see that the Auth::guest() is a shorthand of the Auth::guard($guard)->guest(). Auth::check() is a:

/**
 * Determine if the current user is authenticated.
 *
 * @return bool
 */
public function check()
{
    return ! is_null($this->user());
}

and Auth::guest() is a opposit of Auth::check():

/**
 * Determine if the current user is a guest.
 *
 * @return bool
 */
public function guest()
{
    return ! $this->check();
}
like image 44
Filip Koblański Avatar answered Oct 10 '22 12:10

Filip Koblański