Naveed
Naveed

Reputation: 929

How do I find which `guard` made the current request in Laravel?

Here is my auth.php:

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

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

],

Now, if both a user and an admin are logged-in in the same browser, how do I check which guard made the request?

Please note that both Auth::guard('admin')->check() and Auth::check() return true no matter who's making the request.

Upvotes: 3

Views: 10816

Answers (3)

Dhairya Lakhera
Dhairya Lakhera

Reputation: 4808

It will return your current guard name such as 'admin'

Auth::getDefaultDriver(); 

Upvotes: 0

Vincent Alamale
Vincent Alamale

Reputation: 11

Get all the guards defined in the application and find which of them the current user logged in with.

$guards = array_keys(config('auth.guards'));

return collect($guards)->first(function($guard){
    return auth()->guard($guard)->check();
});

Upvotes: 1

jdavidbakr
jdavidbakr

Reputation: 195

I am assuming you want to know which guard auth()->user() refers to - which is accessible by auth()->guard()

Unfortunately, there is not an existing function to actually get the name of the guard. You can use auth()->guard()->getName() but that returns the session identifier for the guard (i.e. login_guardname_sha1hash) but if you need it you can extract it:

$guard = auth()->guard(); // Retrieve the guard
$sessionName = $guard->getName(); // Retrieve the session name for the guard
// The following extracts the name of the guard by disposing of the first
// and last sections delimited by "_"
$parts = explode("_", $sessionName);
unset($parts[count($parts)-1]);
unset($parts[0]);
$guardName = implode("_",$parts);

Upvotes: 6

Related Questions