Checking which `guard` is loggedin Checking which `guard` is loggedin php php

Checking which `guard` is loggedin


One way to do this is to extend the Laravel authentication class in the IoC container to include, for instance, a name() method that check which guard is used for the current session, and calls user() on that Guard instance.

Another way is to simply use an if-statement in your Blade template:

@if(Auth::guard('admin')->check())    Hello {{Auth::guard('admin')->user()->name}}@elseif(Auth::guard('user')->check())    Hello {{Auth::guard('user')->user()->name}}@endif

However, this is a little dirty. You can clean this up a bit by using a partial, or by passing the view a variable containing the guard name, either directly from your Controller, or via a ViewComposer, and then doing:

Hello {{Auth::guard($guardName)->user()->name}}

in your View.

Extending Laravel's authentication is your best option, imo.


Since Laravel 5.5, this is easy to do with the @auth template directive.

@auth("user")    You're a user!@endauth@auth("admin")    You're an administrator!@endauth@guest    You're not logged in!@endguest

Reference: https://laravel.com/docs/5.6/blade#if-statements


This will get the guard name that is used for current logged in user

Auth::getDefaultDriver()

When you log in, by default it will get you the:

'web'

Dependable through which guard you've been logged in it will get you that guard name.

This is not applicable for APIs!!! Because APIs in laravel by default don't use session.