Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vincej's avatar
Level 15

Can't Make Auth::guard work as expected.

I am using Auth::guard to check which guard is being used during the logout. If it is an admin guard, then I wish to redirect to the admin login, otherwise it goes to a users login.

My assumption is that Auth::guard('admin') checks to see if the guard is indeed of type admin. If so it progresses with the if statement.

However, it is not working the way I expect. I check my guard with a dd(Auth::guard()) and it is definitively a web guard. BUT regardless, the Auth::guard('admin') is still letting it through.

What am I doing wrong? Is my assumption re Auth::guard wrong? Many Thanks !

  if (Auth::guard('admin') ) {

            $this->guard()->logout();

            $request->session()->flush();

            $request->session()->regenerate();  /*dd('line 85');*/

            return redirect('admin-login');
        }
        else {

            $this->guard()->logout();

            $request->session()->flush();

            $request->session()->regenerate();  /* dd('line 96');*/

            return redirect('/login');
        }


0 likes
31 replies
jimmck's avatar

@vincej

Are you using it as expected? Are you looking at the code and stepping in the PHPStorm debug? Its the fastest way.

https://laravel.com/docs/5.4/authentication#protecting-routes

Accessing Specific Guard Instances

You may specify which guard instance you would like to utilize using the guard method on the  Auth facade. This allows you to manage authentication for separate parts of your application using entirely separate authenticatable models or user tables.

The guard name passed to the guard method should correspond to one of the guards configured in your auth.php configuration file:

if (Auth::guard('admin')->attempt($credentials)) {
    //
}
vincej's avatar
Level 15

@jimmck Heah Jim, thanks for coming back.

We had a national internet outage yesterday afternoon, just as I was about to respond to you :(

Looking at the Laravel api, Looking the AuthenticatesUsers.php line 170, there is a function which does get the guard. Once I have the guard I can test for it.

 protected function guard()
    {
        return Auth::guard();
    }

If I call that function, and do dd($this->guard()); I get an array in a weird (json?) format which does contain the guard name.

SessionGuard {#395 ▼
  #name: "web"
  #lastAttempted: null
  #viaRemember: false
  #session: Store {#379 ▶}
  #cookie: CookieJar {#378 ▶}
  #request: Request {#38 ▶}
  #events: Dispatcher {#23 ▼
    #container: Application {#2}
    #listeners: array:3 [▶]
    #wildcards: array:1 [▶]
    #queueResolver: Closure {#24 ▶}
  }
  #loggedOut: false
  #recallAttempted: false
  #user: User {#404 ▶}
  #provider: EloquentUserProvider {#389 ▶}
}

Question How do I extract the name out of the object/array? Many thanks !

vincej's avatar
Level 15

Multi Authentication in Laravel ( a pain)

The story so far: Thanks to jfadich on SO I have got as far as trying getDefaultDriver method which does indeed return the default driver web. However, I need to get the driver in use. This means when I log out from the admin site, I need to be able to test which driver is in use, and if admin, return the admin login page. I will always get the default ie 'web', even if I am using an admin guard? So, jfadich has asked to see my guard set up:

  'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    'admin'=>[
        'guard' => 'admin',
        'passwords' => 'admins',
     ],




  'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],

        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],
    ],




  'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
        ],


         'admins' => [
            'driver' => 'eloquent',
            'model' => App\Models\Admin::class,
        ],

      
    ],

jimmck's avatar

@vincej Hey, SessionGuard is an object. It has gettters for all its members, like getName() to get the name of guard.

Here is the doc

https://laravel.com/api/5.3/Illuminate/Auth/SessionGuard.html

Again, and why I gently stress this. You have a great tool with PHPstorm. You said you got the debugger working. dd is nice in a pinch but the output clearly shows an object. And you can quickly in your project at the object to verify it.

vincej's avatar
Level 15

@jimmck Thanks jim. I did have Storm debugger working, then, I upgraded my Linux version, which requires a 100% OS reinstall and rebuild of the PC. I also upgraded Storm as well, and between the two upgrades I have not yet reinstalled the debugger. Top of my list, once I get this darned thing fixed - promise !

Whats with all the hash # ??

Snapey's avatar

from the link posted by @jimmck

  if (Auth::guard->getName() == 'admin' ) {
1 like
jimmck's avatar

@vincej Well I hope the doc helps. It should be no real issues with those changes. I moved up to PHP 7.2, using Mac homebrew installs of MySql and Apache.

Just make sure to update your extensions. For future refs what are current specs?

OS, PHP, MySQL and key extensions? php -m

Time invested up front pays off with installing tools.

vincej's avatar
Level 15

@Snapey @jimmck

Many Thanks for that Snapey !

Tried your statement, but I got an error from your statement:

Parse error: syntax error, unexpected -> (T_OBJECT_OPERATOR)

So I tried it like this:

dd(Auth::guard()->getName());

And it does not return the admin guard. In fact of you do a dd() on it you get:

"login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d"

vincej's avatar
Level 15

@jimmck

Current specs of current system is:

Linux Mint 18.1 ( this uses Ubuntu 16.04 LTS at it's core)

PHP 7.0 ( I want to upgrade again to 7.2)

Apache 2.4.18

MySQL 5.7.18

Storm 2017

Laravel 5.4

Snapey's avatar

sorry, try

 if (Auth::guard()->getName() == 'admin' ) {
vincej's avatar
Level 15

@jimmck

I bought Matt Stauffers book a few weeks ago which is also very helpful.

I would really like some advice on using the API docs. In my efforts to solve this multi-authentication problem I have indeed been looking into the source code for Laravel, specifically the trait AuthenticatesUsers.php and others.

I see funky methods which are not featured in the user docs. So I try to find them in the API docs. BUT, there must be a secret to quickly finding stuff in the API, as I have found that you can dig around looking for 10 minutes at a time before you might find the method. What is the secrete, or is this just an experience thing ?

Thanks !!

vincej's avatar
Level 15

@Snapey, like I said above it does not test for 'admin'. If I have the right doc entry Jim refers to, it returns,

Get a unique identifier for the auth session value. returns a string

I learned from SO that Auth::getDefaultDriver() does return web as a string. But I need to find the guard in use in the admin app.

If I use $this->guard() I get an array with the guard (see above) to be used during authentication as per the comments on L 166 of AthenticatesUsers.php

vincej's avatar
Level 15

@snapey for clarity, Auth::guard()->getName() returns

login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d

Snapey's avatar

so name seems to be a unique token to the guard and probably includes session data?

is web within that string the name of the guard?

vincej's avatar
Level 15

@snapey no, web is the default guard which I use for "users" who login through the users login. admin guard is for the admins. All these tests have been done loggin gout of admin side. I have posted my guard set up above. For clarity, if I log out of the admin side I want to be redirected to the admin login page. To achieve this, I want to be able to test for which guard is in use.

jfadich's avatar

How is the admin guard set up and applied? Is there an admin guard configured in config/auth.php? Could you post the guards section of your config/auth.php file and also how the guard is being applied whether that is in the routes or controller middleware?

Snapey's avatar

yes I know, but in the example of the guard object you posted earlier, the name was 'web'

if you are, as you say, testing with admin guard why was name not = admin

Snapey's avatar

as suspected

public function getName()
{
    return 'login_'.$this->name.'_'.sha1(static::class);
}

so login is static, then underscore and the name. and then a sha hash of the object

name is defined as

/**
 * The name of the Guard. Typically "session".
 *
 * Corresponds to driver name in authentication configuration.
 *
 * @var string
 */
protected $name;
vincej's avatar
Level 15

@jfadich the guard layout is posted on page 1. I apply the guard middleware in the controller thus:

   public function __construct(){

        $this->middleware('auth:admin');
    }

@Snapey I have no idea why at the point of logout it should be coming out as web when I have been using an admin guard. The logout route has no middleware attached to it.

vincej's avatar
Level 15

@snapey @jfadich

Guys, my wife has just called me, and demands I come home as it's Fri. Heaven knows how late it is in the UK, 11.20pm! so I will have to suspend this conversation till monday. I hope you guys will bear with me, as truly, multi- authetication is a major pain in Laravel no one so far has managed to help me fix this. I have even tweeted Taylor about it. I'm hoping he will blog about it next week. It appears that most people just use 2 login screens and 2 logout screens which for me is really messy.

As always Many Thanks, have a good one !!!

Snapey's avatar

you could use a regex or explode

$guardName =Auth::guard()->getName();
$parts = explode('_',$guardName);
$guard = $parts[1];
jfadich's avatar

@vincej Sorry I saw that after I posted. I assume that constructor you posted is for the admin controller. I think I may see the problem. What middleware is applied to the logout route? Based on what's been said so far I'm willing to be it's web. So even if they logged in through the 'admin' guard, the logout is only checking the web guard. So either create two logout routes that link the appropriate one from the admin and web interfaces respectively or check which guard is logged in before logging out.

if (Auth::guard('admin')->check() ) {
    $loginRedirect = '/admin-login';
} else {
    $loginRedirect = 'login';
}

$this->guard()->logout();  // this shouldn't be necessary if you're flushing the session anyway.

$request->session()->flush();

$request->session()->regenerate();  

return redirect($loginRedirect);
jimmck's avatar

@vincej Laravel documentation is very brief and lacking in the implementation details. As @Snapey pointed out with the getName() code snippit, the name is a concatenation of data to create a unique id. The documentation describes none of that. Effort has to made to read the code. In a one man shop that is a prerequisite. That and experience using and implementing things like Gates and Latches. Common data structures.

vincej's avatar
Level 15

@jimmck yup, for the last few w3ks I have been studying the API together with the source. I just wish it was easier to find what you are looking for in the API. I can spend 10-15 mins trying to find a single method. Any tips on how to find stuff quickly?

jimmck's avatar

@vincej Hy. You sound frustrated. Been there. Many times. That's why I am stressing the whole PHPStorm debug bit. Its a great tool. You can look directly at your project and the external code. One thing I LOVE about PHP is composer. After years or DLL Windows API hell and more years Java JAR hell. Its nice after getting comfortable with the "Composer Fire Dance"! You gotta know basic stuff like types, objects and common data structures. And know how to search for info on that. Especially in a one person shop. Quickly is a Very relative term. But for a reference. I don't use Laravel authentication or Eloquent or Roles simply because I have so much experience using other types. But I saw your issues and your dump and die and immediately saw the reference to a SessionGuard and search the laravel folder ion the composer vendor folder. Then saw the terse incomplete API documentation. You have to look around and have an idea of what concepts and terms you are looking for.

https://www.google.com/search?q=laravel+SessionGuard&oq=laravel+SessionGuard&aqs=chrome.0.69i59j0j69i60.24433j0j7&sourceid=chrome&ie=UTF-8#q=laravel+authentication+tutorial

But it starts with reading the docs and looking at the code with best available tools.

vincej's avatar
Level 15

@jimmck Once again, many thanks for al your help and feedback!

However, you have got me very wrong, I am actually very chill and not frustrated at all. Just always eager to overcome obstacles and always learn more. I am most certainly not a beginner. Perhaps that might give that impression, but that might be because I'm a detail person.

My application as it stands today is many, many thousands of lines of Laravel, Javascript and Jquery code. Out of the box Authentication as given in the user docs is a walk in the park. That is not the challenge I am trying to overcome. I am wanting to deliver multi-authentication with multiple user types, and very specific user login and logout pages. Everything I have read and watched states that Laravel has major, major weaknesses in this area. Indeed some commentators state it can not be done with Laravel's current authentication structure, such is the gravity of the challenge. This is not only my opinion but the opinion of many commentators, and looking at the dialogue over the last 2 pages, it appears that reality is borne out. However, I have an idea of my own on how to overcome the challenge. I'm optimistic.

Lastly, in my effort to accelerate my learning of Laravel, I have been searching through the API docs as you recommend. As already stated, I find their accessibility could be improved.

As always, many thanks for all your help, time and support!!

Next

Please or to participate in this conversation.