How to define a policy method with no argument in Laravel 5.2?

时光总嘲笑我的痴心妄想 提交于 2019-12-11 01:57:41

问题


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

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

        //...
    }
}

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


回答1:


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)
    {
        if($user->is_admin)
        {
            return true;
        }

        return false;
    }
}

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

        //...
    }
}

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

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

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



来源:https://stackoverflow.com/questions/37242321/how-to-define-a-policy-method-with-no-argument-in-laravel-5-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!