Checking which `guard` is loggedin
Asked Answered
A

8

43

I have a multiauth laravel 5.2 app, with the fallowing guards defined on config/auth.php:

...
'admin' => [
    'driver' => 'session',
    'provider' => 'admin',
],
'user' => [
    'driver' => 'session',
    'provider' => 'user',
],
...

So, admin and user.

The problem resides in the view layer, since this two loggedin guards share some views, ex:

Hello {{Auth::guard('admin')->user()->name}}

In this case the guard is hardcoded into the view to be always admin (it gives error when loggedin guard is user), but, to avoid have to do another equal view just for this little change, I would like have it dinamic, something like:

Hello {{Auth::guard(<LOGGEDIN GUARD>)->user()->name}}

PS: I know that this could be achieved getting the corresponding url segment, ex: www.site.com/pt/user/dasboard which in the case it would be segment 2, but this way the app would lose scalability, since in the future the corresponding segment may not be the same (2 in the example above)

Autohypnosis answered 17/8, 2016 at 14:40 Comment(4)
Have a look here at getGuard() and how it's implemented in Laravel's auth area. Think that will get you going in right direction.Multiped
Thanks for the reply, unfortunately Auth::guard($this->getGuard()) triggers Method [getGuard] does not exist. . I guess it's a 5.1 feature, i also checked #35625061 , with same resultAutohypnosis
Right, since you're not in the auth class and the method is protected, you can't use $this to access it. But you might be able to access with something like Auth::guard(Auth::getGuard()) but I'm not positive.Multiped
also didn't work, ...class 'Illuminate\Auth\SessionGuard' does not have a method 'getGuard'Autohypnosis
S
77

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.

Sirius answered 17/8, 2016 at 16:41 Comment(4)
Thanks but that also would remove scalability from the app since the I would be fixed to the admin/user guardAutohypnosis
Very true. That's why extending the Laravel authentication is the better option here.Sirius
@Sirius what if you're logged as both?Mckissick
return me : auth guard [user] is not defined ... but [admin] worked and return false for non admin new userNarial
D
13

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.

Decarbonate answered 31/10, 2019 at 8:14 Comment(3)
Auth::getDefaultDriver() is get $this->app['config']['auth.defaults.guard']; it should be always the config valueAmaro
Not if you have multiple and are used dynamically... with that ^ you will get the default that is hard coded in config.auth fileDecarbonate
This is the default driver from the config, not the the one that is used for current logged userCancer
C
11

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

Craniometry answered 29/6, 2018 at 18:34 Comment(1)
i tried with your answer, but when i login with auth('admin'),it show content of admin but it still shows content of guest, i dont know why?!Doorn
M
8

In new versions of laravel use:

Auth::getDefaultDriver()

I recommend to use global helper function like

function activeGuard(){

foreach(array_keys(config('auth.guards')) as $guard){

    if(auth()->guard($guard)->check()) return $guard;

}
return null;
}
Marinemarinelli answered 4/11, 2019 at 13:44 Comment(0)
N
4

Depends of Harat answer, I built a Class names CustomAuth, and it give me easy access to Auth facade methods: user() and id().

<?php

namespace App\Utils;

use Illuminate\Support\Facades\Auth;

class CustomAuth{
    static public function user(){
        return Auth::guard(static::activeGuard())->user() ?: null;
    }

    static public function id(){
        return static::user()->MID ?: null;
    }

    static private function activeGuard(){

        foreach(array_keys(config('auth.guards')) as $guard){

            if(auth()->guard($guard)->check()) return $guard;

        }
        return null;
    }
}

Nazareth answered 2/12, 2019 at 20:1 Comment(0)
E
1

using auth()->guard($guard)->getName() will return two different type of values

login_admin_59ba36addc2b2f9401580f014c7f58ea4e30989d

if is an admin guard

login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d

if is a web guard or depending on your use case a user guard. So you can test against that.

so a simple use case can be as stated below

 if(str_contains(auth()->guard($guard)->getName(), 'admin')){
      dd('is admin');
   }

here if is an admin, it will show 'is admin' otherwise you get the default

Evie answered 11/2, 2021 at 12:58 Comment(0)
N
1

In my case I had up and running project with too often usage of auth()->user() thus I was obligated to find a way to keep using multiple guards across my app.


Use a middleware to handle overwriting the value the default guard.

Add a custom web middleware to your web group within kernel.php

protected $middlewareGroups = [
        'web' => [
            .....
            //This cool guy here
            \App\Http\Middleware\CustomWebMiddleware::class,
        ],

Use CustomWebMiddleware.php content:

<?php

namespace App\Http\Middleware;


use Closure;

class CustomWebMiddleware
{

    public function handle($request, Closure $next)
    {
        $customGuard = 'custom-guard-name-goes-here';
        if (auth($customGuard)->check()) {
            config()->set('auth.defaults.guard', $customGuard);
        }

        // if you have multiple guards you may use this foreach to ease your work.
        /*$guards = config('auth.guards');
        foreach ($guards as $guardName => $guard) {
            if ($guard['driver'] == 'session' && auth($guardName)->check()) {
                config()->set('auth.defaults.guard', $guardName);
            }
        }*/

        return $next($request);
    }


}

Nicknack answered 24/9, 2021 at 16:6 Comment(0)
G
0
Auth::getDefaultDriver()

Above will return the current guard, in your case (user or admin)

Gerontocracy answered 3/8, 2021 at 12:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.