Modify input before validation on Laravel 5.1

穿精又带淫゛_ 提交于 2019-12-01 02:31:25
shock_gone_wild

This is a tricky one. I only figured out one way to achieve what you want.

The main point is, that it has no effect for the Validator if you change the Request Values in the rules() function.

You could do a workaround by adding a function to your UserCreateRequest:

protected function getValidatorInstance() {
    $this->sanitize();
    return parent::getValidatorInstance();
}

This overrides the parent's getValidatorInstance();

The parent's getValidatorInstance() method includes

    return $factory->make(
        $this->all(), $this->container->call([$this, 'rules']), $this->messages(), $this->attributes());

Which is reached before your code in the rules() function, so the old values (not affected by the changes in rules()) of $this->all() are used.

If you override that function in your own RequestClass you can manipulate the Request values before calling the actual parent's method.

UPDATE (L5.5)

If you are using the Controllers validate function you could do something like that:

    $requestData = $request->all();

    // modify somehow
    $requestData['firstname'] = trim($requestData['firstname']);

    $request->replace($requestData);

    $values = $this->validate($request, $rules);

You can do this by modifying the request and setting the input value.

$request->request->set('key', 'value');

Or, if you prefer the request helper method.

request()->request->set('key', 'value');

If you are using a request MyClassRequest for keeping your validation then simply override all() method of Request class

public function all()
{
    $attributes = parent::all();

    //you can modify your inputs here before it is validated
    $attribute['firstname'] = trim($attribute['firstname']);
    $attribute['lastname'] = trim($attribute['lastname']);

    return $attributes;
}

Hope this helps.

These answers no longer work for me in 5.5

you can use

protected function validationData()
{
    $this->request->add([
        'SomeField' => '..some code to modify it goes here'
    ]);
    return $this->request->all();
}

the add method on request overwrites any existing input for that key.

You can see why this works in Illuminate\Foundation\Http\FormRequest, if you follow the trail

/**
 * Get data to be validated from the request.
 *
 * @return array
 */
protected function validationData()
{
    return $this->all();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!