42

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)

miken32
  • 42,008
  • 16
  • 111
  • 154
Miguel
  • 1,579
  • 5
  • 18
  • 31
  • Have a look [here](https://github.com/laravel/framework/blob/2a38acf7ee2882d831a3b9a1361a710e70ffa31e/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php#L218) at `getGuard()` and how it's implemented in Laravel's `auth` area. Think that will get you going in right direction. – camelCase Aug 17 '16 at 15:01
  • 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 http://stackoverflow.com/questions/35624561/laravel-5-the-difference-between-authguardthis-getguard-loginuser , with same result – Miguel Aug 17 '16 at 15:11
  • 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. – camelCase Aug 17 '16 at 16:03
  • also didn't work, `...class 'Illuminate\Auth\SessionGuard' does not have a method 'getGuard'` – Miguel Aug 17 '16 at 16:44

8 Answers8

73

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.

tomfrio
  • 993
  • 7
  • 16
14

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.

lewis4u
  • 14,256
  • 18
  • 107
  • 148
  • 2
    Auth::getDefaultDriver() is get $this->app['config']['auth.defaults.guard']; it should be always the config value – Shiro Oct 29 '20 at 15:40
  • 2
    Not if you have multiple and are used dynamically... with that ^ you will get the default that is hard coded in config.auth file – lewis4u Oct 29 '20 at 15:42
  • 2
    This is the default driver from the config, not the the one that is used for current logged user – Mladen Janjetovic Jun 17 '21 at 20:18
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

miken32
  • 42,008
  • 16
  • 111
  • 154
  • 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?! – The Manh Nguyen Nov 19 '18 at 10:56
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;
}
Harat
  • 1,340
  • 1
  • 17
  • 20
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;
    }
}

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

Peter
  • 1,124
  • 14
  • 17
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);
    }


}

Mohamed Mo Kawsara
  • 4,400
  • 2
  • 27
  • 43
0
Auth::getDefaultDriver()

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

Damilare Koiki
  • 341
  • 3
  • 11