如何在Laravel 5.2中定义不带参数的策略方法? [英] How to define a policy method with no argument in Laravel 5.2?

查看:87
本文介绍了如何在Laravel 5.2中定义不带参数的策略方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时需要检查用户授权是否有不带参数的操作,例如create/store方法:

It's sometimes necessary to check user authorization for an action with no argument like create/store method:

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中使用authorize方法:

and use the authorize method in PostController:

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

        //...
    }
}

但是,似乎没有参数的策略方法不能与控制器上的authorize方法相对应,并且授权始终会失败.

But it seems that a policy method with no arguments can not correspond to the authorize method on a controller and authorization always fails.

推荐答案

如果定义的策略方法没有这样的参数:

If a policy method has been defined with no arguments like this:

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

您可以使用如下所示的authorize方法:

You may use the authorize method like this:

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);

        //...
    }
}

并通过使用@can Blade指令在刀片模板中:

and within blade templates by using the @can Blade directive:

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

还可以使用Gate外观,User模型或policy助手.

It's also possible to use Gate facade, the User model or the policy helper.

这篇关于如何在Laravel 5.2中定义不带参数的策略方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆