Laravel 5.1 Modify input before form request validation

后端 未结 5 928
感情败类
感情败类 2020-12-20 21:05

Is there a way to modify input fields inside a form request class before the validation takes place?

I want to modify some input date fields as follows but it doesn

5条回答
  •  时光说笑
    2020-12-20 21:29

    I took an alternative approach to this, as I want to be able to use $model->fill($validated); in my controllers. As such, I need to ensure that checkboxes have been included as false where they would otherwise be excluded from the array.

    So, I created a trait, in app\Traits\ConvertBoolean.php, as follows:

    boolean_attributes) && is_array($this->boolean_attributes)) {
    
                $attrs_to_add = [];
    
                foreach ($this->boolean_attributes as $attribute) {
                    $attrs_to_add[$attribute] = $this->has($attribute);
                }
    
                $this->merge($attrs_to_add);
            }
        }
    }
    

    This trait looks for the existence of an array $this->boolean_attributes in the request. If it finds it, it goes through each one and adds the attribute to the request data with the value set to the presence of the attribute in the original request data.

    It disregards the value of the HTML form's checkbox value. In most cases, this won't be a problem, but you could change the logic in the trait to look for specific values, if required.

    Now that I have this trait, I can then use it in any request, like so:

    use App\Traits\ConvertBoolean;
    
    class MyUpdateRequest extends FormRequest
    {
        use ConvertBoolean;
    
        protected $boolean_attributes = ['my_checkbox'];
    
        // ... other class code
    
    
        public function rules()
        {
            // Note that the data is added to the request data,
            // so you still need a validation rule for it, in
            // order to receive it in the validated data.
            return [
                'my_checkbox' => 'boolean',
                // other rules
            ];
        }
    }
    

    If you want to use $this->prepareForValidation() in your request, this is still possible.

    Change MyRequest, as follows:

    use App\Traits\ConvertBoolean;
    
    class MyUpdateRequest extends FormRequest
    {
        use ConvertBoolean {
            prepareForValidation as traitPrepareForValidation;
        }
    
        protected function prepareForValidation() {
    
            // the stuff you want to do in MyRequest
            // ...
    
            $this->traitPrepareForValidation();
        }
    
        // ...
    }
    

提交回复
热议问题