How to modify or change input data before form request validation

How to modify or change input data before form request validation?

Solution: Override the prepareForValidation() method of the FormRequest

So in the form request file:

class CreateAbcdefgRequest extends APIRequest
{
protected function prepareForValidation()
{
    if ($this->has('first_name'))
        $this->merge(['first_name'=>'Mr '.$this->first_name]);
}

As of laravel 5.4 you can override the prepareForValidation method of the ValidatesWhenResolvedTrait to modify any input. Something similar should be possible for laravel 5.1.

Example in your Request

/**
 * Modify the input values
 *
 * @return void
 */
protected function prepareForValidation() {

    // get the input
    $input = array_map('trim', $this->all());

    // check newsletter
    if (!isset($input['newsletter'])) {
        $input['newsletter'] = false;
    }

    // replace old input with new input
    $this->replace($input);
}

Leave a Reply

Your email address will not be published. Required fields are marked *