简体   繁体   中英

Laravel 5.4 Validation Using Form Requests

I want to use Form Requests to validate Model so i started by create php artisan make:request TaskRequest and after i add in TaskRequest class `

 public function rules()
    {
        return [
            'name' => 'required|min:5',
        ];
    }   
    public function messages()
    {
        return [
            'name.required' => 'A title is required',
        ];
    }
`

and in My logic

Route::post('/tasks',function (\App\Http\Requests\TaskRequest $request){

    $task = new \App\Task();
    $task->name = $request->input("name");
    $task->save();

    return response()->json(['task was created',$task], http_response_code());
});

So when i try to add a task i get error HttpException, This action is unauthorized.,AuthorizationException ...

It was work for me without Validation. So how can i fix this issue ?

Every (self-created) request has an authorize function that determines if the user is allowed to send the request. This can be useful to check for admin privileges or similar.

In you case, you can simply return true . More information can be found in the corresponding docs

Your authorize function in your TaskRequest would look like this:

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

In your custom request class for "form request" which contains the validation logic pass return:true; instead of return:false; and then it will work like a charm.

The code will look like something as following,

    namespace App\Http\Requests;

    use Illuminate\Foundation\Http\FormRequest;

    class portfolioValidate 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 [
                'title'=> 'required',
                'content'=> 'required'
            ];
        }
    }

as you can use middleware to make authentication for the page which contains this form... so we don't need that authorization in the FormRequest class. So returning true will make it(validation) authorized for all cases.

I think now it is clear to everyone now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM