Рубрики
Uncategorized

Пользовательский класс проверки запроса формы laravel (запрос формы использует правило())

Автор оригинала: David Wong.

Мы можем использовать запрос формы для инкапсуляции кода проверки формы, чтобы упростить логику кода в контроллере и сосредоточиться на бизнесе. Независимая логика проверки формы может быть повторно использована в других запросах. Прочитав несколько статей, большинство из них посвящены тому, как создать запрос. На первый взгляд кажется, что логика отделена от бизнеса, но она не используется повторно. Он слишком устал, чтобы создавать новый класс запросов для бизнеса. Я просто помещаю всю проверку формы проекта в класс запроса для достижения высокой степени использования повторяемости, ниже приведена конкретная реализация.

Сначала создайте запрос

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!'); 
            }
    }

Соответствующий файл шаблона

< label for = "name" class = "col-sm-2 control label" > name < / label > {!! csrf_field() !!}
< input type = "text" class = "form control" id = "name" name = "student [username]" placeholder = "please enter student name" value = "{old ('student ') ['username']}"} ">

{{ $errors->first('Student.userName') }}

< label for = "age" class = "col-sm-2 control label" > age < / label >
< input type = "text" class = "form control" id = "age" name = "student [userage]" placeholder = "please enter student age" value = "{old ('student ') ['userage']}"} ">

{{$errors->first('Student.userAge')}}

< label for = "age" class = "col-sm-2 control label" > address < / label >
< input type = "text" class = "form control" id = "addr" name = "student [addr]" placeholder = "please input address" >

{{$errors->first('Student.addr')}}

< label class = "col-sm-2 control label" > gender < / label >
! [QQ screenshot 20170613152555. PNG] (http://upload-images.jianshu.io/upload "images / 2825702-f008b65789a425f4. PNG? Imagemogr2 / Auto original / strip% 7cimageview2 / 2 / w / 1240)

{{ $errors->first('Student.userSex') }}

< button type = "submit" class = "BTN BTN primary" > submit < / button >

Отображение эффекта

Написано в конце

Из текста мы видим, что запросы форм очень мощны и удобны для упрощения проверки данных запросов форм. Здесь я внес некоторые изменения, чтобы сделать правила() повторно используемыми и добавлять только новый запрос. Если есть лучшее решение, пожалуйста, оставьте сообщение.