laravel 哨兵/哨兵,如果用户是角色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25365290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sentry/Sentinel if user is in role
提问by T2theC
I am trying to run a check to see if the current user is in a certain role with Cartalyst's Sentinel/Sentry package.
我正在尝试运行检查以查看当前用户是否在 Cartalyst 的 Sentinel/Sentry 包中担任某个角色。
I have found Sentinel::inRole('admin')but can't seem to get it to work. I want something like this:
我找到了,Sentinel::inRole('admin')但似乎无法让它工作。我想要这样的东西:
if(Sentinel::getUser()->hasRole('admin'){ // do some stuff }
if(Sentinel::getUser()->hasRole('admin'){ // do some stuff }
I've searched and searched for this and can't find an example to work with. Should I be looking more into permissions or something?
我已经搜索并搜索了这个,但找不到可以使用的示例。我应该更多地研究权限吗?
Hopefully someone out there can point me in the right direction.
希望有人能指出我正确的方向。
Cheers
干杯
回答by Suhayb El Wardany
You can use inRolehere, Sentinel::getUser()->inRole('role_slug');. Of course this would only work if a user is logged in.
你可以inRole在这里使用,Sentinel::getUser()->inRole('role_slug');。当然,这仅在用户登录时才有效。
You might wanna change it to something like this to prevent calling inRoleon a non object.
您可能想将其更改为类似的内容,以防止调用inRole非对象。
if ($user = Sentinel::getUser())
{
if ($user->inRole('administrator'))
{
// Your logic
}
}
Hope that helps.
希望有帮助。
回答by jerney
Have your User model extend Cartalyst's 'EloquentUser' model. This model has a getRoles() function that will return the roles for that user. Each user also has an inRole( $role ) function that will return true if the user has the role specified in the parameter.
让您的用户模型扩展 Cartalyst 的“EloquentUser”模型。该模型有一个 getRoles() 函数,该函数将返回该用户的角色。每个用户还有一个 inRole( $role ) 函数,如果用户具有参数中指定的角色,该函数将返回 true。
Extention would look like this:
扩展看起来像这样:
use Cartalyst\Sentinel\Users\EloquentUser;
class User extends EloquentUser implements ... {
....
}
In my opinion this is the cleanest way to accomplish what you want.
在我看来,这是完成您想要的最干净的方式。
If you don't want to do that you could check permissions instead and have your permissions configured like a role
如果您不想这样做,您可以改为检查权限并将您的权限配置为角色
$admin = Sentinel::create()
$admin->permissions = [
'admin' => true,
];
$admin->save();
Then check the user's permissions instead of checking their role
然后检查用户的权限而不是检查他们的角色
if($admin->hasAccess('admin') { // do some stuff }
Hope this helps.
希望这可以帮助。
-Josh E
-乔什E
回答by Alex
I first check if authorized and if so then watch what role
我首先检查是否授权,如果授权,然后看什么角色
so works
如此有效
@if(!Sentinel::guest())
@if(Sentinel::inRole('user'))
<ul class="nav navbar-nav navbar-right">
<li><a href="logout">{{trans('master.logout')}}</a></li>
</ul>
@endif
@endif

