laravel 策略中的方法不返回“管理员”类型用户的按钮

wn9m85ua  于 2022-11-26  发布在  其他
关注(0)|答案(1)|浏览(115)

我在UserPolicies.php文件中的showAdmin()中无法显示Show in dojo.blade.php按钮(仅针对管理员(角色=== 1)),即使是管理员类型的用户,我也看不到该按钮。

  • UserPolicies.php
<?php

namespace App\Policies;

use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class UserPolicy
{
    use HandlesAuthorization;

    /**
     * Create a new policy instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    public function showAdmin(User $user){
        return $user->role === 1;
    }
}
  • DojoController.php
public function show($id)
    {
        $dojo = DojoModel::find($id);
        $this->authorize('showAdmin', Auth::user());
        $fighter = FighterModel::get(['id','name']);
        $master = MasterModel::get(['id','name']);
        return view('dojo.show', compact(['dojo','fighter','master']));
    }
  • dojo.blade.php
@can('showAdmin')
    <a href="{{ url("show-dojo/$d->id") }}" class="btn btn-warning"><i class="fa fa-eye"></i>&nbsp;Show</a>
@endcan

会有什么问题?

cld4siwp

cld4siwp1#

您还需要把模型:

@can('showAdmin', \App\Model\User::class)

@can('showAdmin', auth()->user())

还要确保在AuthServiceProvider.php中注册策略,将其放入protected $policies中,接受Model作为密钥,接受Policy作为其值

protected $policies = [
    User::class => UserPolicy::class,
]

Blade文件中的授权
注册策略

相关问题