【问题标题】:Laravel blade @can policy - stringLaravel 刀片 @can 策略 - 字符串
【发布时间】:2016-07-27 06:15:21
【问题描述】:

我正在使用 Laravel 5.2。所以我正在学习如何处理角色和权限Authorization。一切运行良好。我什至制定了自己的政策 PostPolicy。

现在来解决问题。我将 $post 数据加载到 PostsController 中的视图中,然后加载到刀片中。

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

政策

  public function hasRole($user)
    {
        // just for test
        return true;
    }

现在返回所有内容。

当我更改@can('hasRole', Auth::user()) 从 Auth::user() 到一个字符串,即

@can('hasRole', 'guest')
    <h1>Displaying guest content</h1>
@endcan

在这种情况下,它不会返回任何东西。由于我是 Laravel 的新手,我真的不知道它不起作用。

【问题讨论】:

  • 您链接到的文档声明“为了方便起见,Laravel 提供了@can Blade 指令来快速检查当前经过身份验证的用户是否具有给定的能力。”

标签: php laravel laravel-5 laravel-5.2 laravel-authorization


【解决方案1】:

您可能没有足够仔细地阅读文档。您应该将模型作为第二个参数传递,而不是字符串或用户对象。在你的情况下,你可能应该使用这样的东西:

@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

但问题是您真正想要实现的目标。如果您只想使用用户角色来验证权限,则不需要使用此指令。

您可以添加到您的 User 模型函数以验证当前角色,例如

public function hasRole($roleName) 
{
   return $this->role == $roleName; // sample implementation only
}

现在您可以在刀片中使用:

@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

【讨论】:

  • 感谢您的详细解答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-07
  • 1970-01-01
  • 2018-06-05
  • 2021-10-15
  • 1970-01-01
  • 2016-07-14
  • 2018-04-04
相关资源
最近更新 更多