错误"此操作未经授权。"在Laravel中使用表单请求验证(5.5+)

时间:2017-11-06 02:29:52

标签: php laravel validation laravel-5 authorization

我这样做了一个门:

Gate::define('update-post', function  ($user, Post $post) {
    return $user->hasAccess(['update-post']) or $user->id == $post->user_id;
});

我检查了我的数据库并且它具有更新帖子访问权限,并且用户ID与帖子中的相同。但我得到了:

  

此操作未经授权。

错误。所以我在这里犯了一些错误吗?感谢。

5 个答案:

答案 0 :(得分:11)

我在开始使用Form Requestdata validation类时使用类似的问题(例如,使用php artisan make:request UpdateUserRequest)。

如果您使用Form Request验证数据,那么首先,请检查您是否正确设置了正确的规则以允许其通过。这是在authorize方法中处理的,该方法返回boolean,默认情况下设置为false

namespace App\Http\Requests\Users;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;

class UpdateUserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()   
    {
        /** 
         * By default it returns false, change it to 
         * something like this if u are checking authentication
         */
        return Auth::check(); // <------------------

        /** 
         * You could also use something more granular, like
         * a policy rule or an admin validation like this:
         * return auth()->user()->isAdmin();
         */
    }

    public function rules()
    {
        // your validations...
    }

}

答案 1 :(得分:3)

确保在&#34;授权&#34;上返回 true 方法

public function authorize()
{
    return true;
}

答案 2 :(得分:1)

我没有在return truephp artisan make:request SellRequest时发生了此问题 功能public function authorize()

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class SellRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
        public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'city'=>'required',
            'address'=>'required',
            'type'=>'required',
            'land'=>'required',
            'area'=>'required'
        ];
    }
}

答案 3 :(得分:0)

<?php 
namespace App\Modules\UserManagement\Request;

use Illuminate\Foundation\Http\FormRequest;
use Response;

class UserRequest extends FormRequest
{
     /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }


    public function rules()
    {

        $rules = [
            'full_name' => 'required',
            'email' => 'required|email',
            'password' => 'required',
            're_enter_password' => 'required'
        ];

        return $rules;
    }
}

答案 4 :(得分:0)

就我而言,我没有在Gate::define(...)中进行正确的检查

所以也许再次检查一下该函数的逻辑