检查哪个`guard`已登录 [英] Checking which `guard` is loggedin

查看:85
本文介绍了检查哪个`guard`已登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个multiauth laravel 5.2应用程序,其休闲防护定义在config/auth.php上:

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',
],
...

所以adminuser.

问题出在视图层,因为这两个已登录的守卫共享一些视图,例如:

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

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

在这种情况下,后卫会被硬编码到视图中,始终是admin(当登录后卫是user时会出错),但是,为了避免不得不为这个小的变化而做另一个相等的视图,我会像是动态的,就像:

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:我知道这可以通过获取相应的url段来实现,例如:www.site.com/pt/user/dasboard在第2个段的情况下,但是这样应用程序将失去可扩展性,因为将来相应的段可能会不相同(在上面的示例中为2)

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)

推荐答案

一种方法是在IoC容器中扩展Laravel身份验证类,以包括例如name()方法,该方法检查使用了哪种防护措施当前会话,并在该Guard实例上调用user().

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.

另一种方法是在Blade模板中简单地使用 if语句:

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

但是,这有点脏.您可以通过部分操作或通过直接从Controller或通过ViewComposer向视图传递包含防护名称的变量来进行一些清理,然后执行以下操作:

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}}

在您的视图中.

扩展Laravel的身份验证是您最好的选择,imo.

Extending Laravel's authentication is your best option, imo.

这篇关于检查哪个`guard`已登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆