Check which Guard is logged

Asked

Viewed 226 times

1

I have a 5.2 Standard application, with multiauthentication, the Guards configured in config/auth.php sane:

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

That is to say admin and user.

My problem is in the view, because these two Guards when loggedin share some same views, that’s where the problem is generated:

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

In this case the corresponding Guard is hardcoded to always be the admin (error if Guard user that is loggedin), after some research I did not find anything to indicate me the solution, ie to know if the Guard that is loggedin is user or admin, this way I would use an equal view only with this change. EX solution:

Olá {{Auth::guard(<GUARD QUE ESTEJA LOGIN>)->user()->name}}

PS: I know I would give going by the segment of the url corresponding to Guard, ex: www.site.com/pt/user/dasboard, in this case it would be segment 2, but lose one of the scalability of the app because nothing guarantees that in the future the corresponding segment of the url remains the 2.

1 answer

4

Man, have you thought about it:

$guard    = $this->getGuard();
$provider = $guard->getProvider();
Auth::guard($provider)->get()->name;

Otherwise, something you can do:

if(Auth::guard('admin')->check()){
   Auth::guard('admin')->admin()->name;
}
elseif(Auth::guard('user')->check()){
   Auth::guard('user')->user()->name;
}
  • Obsessed by the answer Diego, but that would take scalability to the app, in the future would have to touch it if the Guards were not the same... I wanted to know the Guard loggedin regardless of the name it may have. The fact that I have to write the name of Guard is what I’m trying to avoid. I’d give a vote for trying to help but I can only do it tomorrow, I already spent my vows today but I won’t forget

  • But the first code of my answer gets the Guard Logged. Isn’t that what you want ? Don’t fix one, but I know how to catch what’s on active ?

  • Nop, making dd($this->getGuard()); in the controller gives: Method [getGuard] does not exist. I also asked on Soen but unsuccessfully: http://stackoverflow.com/questions/38999725/checking-which-guard-is-loggedin/39002084?noredirect=1#comment65357513_39002084

  • I changed the code. It’s not like that anymore.

  • Yeah, but the problem is $this->getGuard(); gives the error I wrote

  • I get it. I’ll think about it some more.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.