Laravel blade @can policy - string

后端 未结 1 1188
醉酒成梦
醉酒成梦 2021-01-23 21:39

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

1条回答
  •  佛祖请我去吃肉
    2021-01-23 22:43

    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')
    
    @can('hasRole', $post)
        

    Displaying Admin content

    @endcan @can('hasRole', $post)

    Displaying moderator content

    @endcan @can('hasRole', $post)

    Displaying guest content

    @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')
    
    
    @if (auth()->check())    
        @if (auth()->user()->hasRole('admin'))
            

    Displaying Admin content

    @elseif (auth()->user()->hasRole('moderator'))

    Displaying moderator content

    @endif @else

    Displaying guest content

    @endif

    0 讨论(0)
提交回复
热议问题