【问题标题】:How to define a policy method with no argument in Laravel 5.2?如何在 Laravel 5.2 中定义没有参数的策略方法?
【发布时间】:2016-09-11 13:24:05
【问题描述】:

有时需要检查用户授权以执行不带参数的操作,例如 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');

        //...
    }
}

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

【问题讨论】:

    标签: laravel laravel-5.2 laravel-authorization


    【解决方案1】:

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

    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);
    
            //...
        }
    }
    

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

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

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

    【讨论】:

    • 它坚持不工作,直到我在授权方法中明确定义类(\App\Post::class).. 使用 App\Post 将不起作用。
    猜你喜欢
    • 2016-12-08
    • 2020-11-25
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 2019-10-03
    • 2016-09-03
    • 2016-12-16
    • 1970-01-01
    相关资源
    最近更新 更多