且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Laravel 5.1上验证之前修改输入

更新时间:2023-12-04 10:26:58

这是一个棘手的问题.我只是想出一种方法来实现您想要的.

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

主要要点是,如果您在 rules()函数中更改请求值,则对验证程序没有影响.

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

您可以通过向UserCreateRequest中添加函数来解决此问题:

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

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

这将覆盖父级的getValidatorInstance();

This overrides the parent's getValidatorInstance();

父级的getValidatorInstance()方法包括

The parent's getValidatorInstance() method includes

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

在rules()函数中的代码之前到达哪个位置,因此使用$ this-> all()的旧值(不受rules()中的更改影响).

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.

如果您在自己的RequestClass中覆盖该函数,则可以在调用实际父级的方法之前操纵Request值.

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

更新(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);