Мы можем использовать запрос формы для инкапсуляции кода проверки формы, чтобы упростить логику кода в контроллере и сосредоточиться на бизнесе. Независимая логика проверки формы может быть повторно использована в других запросах. Прочитав несколько статей, большинство из них посвящены тому, как создать запрос. На первый взгляд кажется, что логика отделена от бизнеса, но она не используется повторно. Он слишком устал, чтобы создавать новый класс запросов для бизнеса. Я просто помещаю всю проверку формы проекта в класс запроса для достижения высокой степени использования повторяемости, ниже приведена конкретная реализация.
Сначала создайте запрос
php artisan make:request CreateUserRequest
Блок кода Createuserrequest
'required|between:2,4', 'Student.userAge' => 'required|integer', 'Student.userSex' => 'required|integer', 'Student.addr' => 'required', ]; //Here I only write part of the fields, and I can define all the fields protected $strings_key = [ 'student. Username' = > user name ', 'student. Userage' = > age ', 'student. Usersex' = > gender ', 'student. Addr' = > address', ]; //I've only written part of the information here, which can be defined on demand protected $strings_val = [ 'required' = > 'is required', 'min' = >, 'Max' = > 'Max: Max', 'between' = > 'length between: min and: Max', 'Integer' = > 'must be an integer', 'sometimes'=> '', ]; /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { Return true; // modify to true } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $rules = $this->rules; //Add different validation rules according to different situations If (request:: getpathinfo() = = '/ save') // if it is a save method { $rules['Student.addr'] = 'sometimes'; } If (request:: getpathinfo() = = '/ Edit') // if it is an edit method { $rules['Student.addr'] = 'required|min:5'; } return $rules; } //Error messages returned to the foreground public function messages(){ $rules = $this->rules(); $k_array = $this->strings_key; $v_array = $this->strings_val; foreach ($rules as $key => $value) { $new_arr = expand ('|, $value); // split into arrays foreach ($new_arr as $k => $v) { $head = strstr ($V, ':', true); // intercept: Previous string if ($head) {$v = $head;} $array[$key.'.'.$v] = $k_array[$key].$v_array[$v]; } } return $array; } }
Конкретный способ управления
/** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function save(\App\Http\Requests\CreateUserRequest $request) { //Form validation is automatically called here //Continue to execute downward after the verification is successful $data = $request->input('Student'); if(User::create($data)){ Return direct ('/') - > with ('success','successfully added! '); }else{ Return direct ('/ create') - > with ('error ','add failed!'); } }