Laravel Blade @can 策略 - 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36457983/
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
Laravel blade @can policy - string
提问by Peter
I am using Laravel 5.2. So I'm learning about how to deal with roles and permissions Authorization. Everything runs fine. I even made my own policy PostPolicy.
我正在使用 Laravel 5.2。所以我正在学习如何处理角色和权限Authorization。一切运行良好。我什至制定了自己的政策 PostPolicy。
And now to the problem. I load the $post data into the view in the PostsController which then loads in blade.
现在来解决这个问题。我将 $post 数据加载到 PostsController 的视图中,然后加载到刀片中。
PostsController:
帖子控制器:
public function show($id)
{
$post = Post::find($id);
return view('posts.show', compact('post'));
}
posts/show.blade.php:
帖子/show.blade.php:
@section('content')
<!-- begin -->
@can('hasRole', Auth::user())
<h1>Displaying Admin content</h1>
@endcan
@can('hasRole', Auth::user())
<h1>Displaying moderator content</h1>
@endcan
@can('hasRole', Auth::user())
<h1>Displaying guest content</h1>
@endcan
Policy:
政策:
public function hasRole($user)
{
// just for test
return true;
}
Now that returns all the content.
现在返回所有内容。
When I change the @can('hasRole', Auth::user())
from
Auth::user() to a string, i.E.
当我将 @can('hasRole', Auth::user())
Auth::user() 更改为字符串时,即
@can('hasRole', 'guest')
<h1>Displaying guest content</h1>
@endcan
In this case it doesn't return anything. As I am new to Laravel, I really don't know it doesn't work.
在这种情况下,它不会返回任何内容。由于我是 Laravel 的新手,我真的不知道它行不通。
回答by Marcin Nabia?ek
You probably haven't read docs carefully enough. You should pass as the 2nd argument a model, not a string or user object. In your case, you should probably use something like this:
您可能没有足够仔细地阅读文档。您应该将模型作为第二个参数传递,而不是字符串或用户对象。在你的情况下,你可能应该使用这样的东西:
@section('content')
<!-- begin -->
@can('hasRole', $post)
<h1>Displaying Admin content</h1>
@endcan
@can('hasRole', $post)
<h1>Displaying moderator content</h1>
@endcan
@can('hasRole', $post)
<h1>Displaying guest content</h1>
@endcan
But the question is what you really want achieve. If you want to use user roles only to verify permissions, you don't need to use this directive.
但问题是你真正想要达到的目标。如果您只想使用用户角色来验证权限,则不需要使用此指令。
You can add to your User
model functions to verify current roles for example
例如,您可以添加到User
模型函数以验证当前角色
public function hasRole($roleName)
{
return $this->role == $roleName; // sample implementation only
}
and now you can use in your blade:
现在你可以在你的刀片中使用:
@section('content')
<!-- begin -->
@if (auth()->check())
@if (auth()->user()->hasRole('admin'))
<h1>Displaying Admin content</h1>
@elseif (auth()->user()->hasRole('moderator'))
<h1>Displaying moderator content</h1>
@endif
@else
<h1>Displaying guest content</h1>
@endif