3

有时需要检查用户授权以获取没有参数的操作,例如 create/store 方法:

class PostPolicy
{
    use HandlesAuthorization;

    /**
     * Determine if the user can create a new post.
     *
     * @param  \App\User $user
     * @return bool
     */
    public function create(User $user)
    {
        if($user->is_admin)
        {
            return true;
        }

        return false;
    }
}

并使用 PostController 中的授权方法:

class PostController extends Controller
{
    /**
     * Show the form for creating a new post.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $this->authorize('create');

        //...
    }
}

但似乎没有参数的策略方法无法对应控制器上的授权方法,并且授权总是失败。

4

1 回答 1

5

如果一个策略方法被定义为没有像这样的参数:

class PostPolicy
{
    use HandlesAuthorization;

    /**
     * Determine if the user can create a new post.
     *
     * @param  \App\User $user
     * @return bool
     */
    public function create(User $user)
    {
        return $user->is_admin;
    }
}

您可以像这样使用授权方法:

class PostController extends Controller
{
    /**
     * Show the form for creating a new post.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $this->authorize('create', \App\Post::class);

        //...
    }
}

并使用@canBlade 指令在刀片模板中:

@can('create', \App\Post::class)
    <!-- The Current User Can Update The Post -->
@endcan

也可以使用Gate外观、User模型或policy助手。

于 2016-05-16T18:58:52.990 回答