Laravel blade @can policy - string

こ雲淡風輕ζ 提交于 2020-07-16 06:10:12

问题


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.

And now to the problem. I load the $post data into the view in the PostsController which then loads in blade.

PostsController:

public function show($id)
{
    $post = Post::find($id);

    return view('posts.show', compact('post'));
}

posts/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', '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.


回答1:


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

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


来源:https://stackoverflow.com/questions/36457983/laravel-blade-can-policy-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!