How to validate Route Parameters in Laravel 5?

后端 未结 4 1795
無奈伤痛
無奈伤痛 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:08

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

提交回复
热议问题