gpt4 book ai didi

php - Laravel blade @can 策略 - 字符串

转载 作者:行者123 更新时间:2023-12-02 04:11:36 26 4
gpt4 key购买 nike

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

现在开始讨论问题。我将 $post 数据加载到 PostsController 的 View 中,然后将其加载到 Blade 中。

帖子 Controller :

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 的新手,我真的不知道它行不通。

最佳答案

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

@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
}

现在您可以在 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

关于php - Laravel blade @can 策略 - 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36457983/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com