How to validate Route Parameters in Laravel 5?

后端 未结 4 1551
灰色年华
灰色年华 2021-02-12 18:23

As you know Laravel 5 changes the way you call the validator, the old way is calling the validator facade, but now there is the ValidatesRequests

4条回答
  •  有刺的猬
    2021-02-12 19:11

    If you plan to do this directly in your controller method you can do something like:

            public function getUser(Request $request)
        {
            $request->merge(['id' => $request->route('id')]);
            $request->validate([
                'id' => [
                    'required',
                    'exists:users,id'
                ]
            ]);
        }
    

    To do this in a custom FormRequest class, add the following:

        protected function prepareForValidation() 
        {
            $this->merge(['id' => $this->route('id')]);
        }
    

    And in your rules method:

        public function rules()
        {
            return [
                'id' => [
                    'required',
                    'exists:users,id'
                ]
            ];
        }
    

提交回复
热议问题