Evren Yurtesen Evren Yurtesen - 1 year ago 149
PHP Question

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:


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:


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

I tried changing the default code to use


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?


Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download