laravel:验证前清理请求数据

ale*_*lex 5 validation rules request laravel

有一个UpdateUserRequest表单请求,它根据在rulesmathod中定义的规则验证字段值.默认情况下,它具有rules()和authorize()方法.我想阻止验证和更新空字段(如密码).

sometimes在规则中使用是没有用的,因为html输入将出现在POST请求中,即使它们是空的.

array:6 [?
 "_method" => "PATCH"
 "_token" => "Cz79rRez2f6MG0tTU17nVwXD0X1lNGH1hA7OORjm"
 "name" => "john"
 "email" => "mymail@gmail.com"
 "password" => ""
 "password_confirmation" => ""

]
Run Code Online (Sandbox Code Playgroud)

所以我应该在使用sometimes规则之前删除POST请求的空键.
问题是:清除Request数组的最佳位置在哪里?
是否有任何laravel构建方法来管理这种情况?

PS:解决方法:
@Bogdon解决方案仍然有效工作,但还有另一种古朴,美观大方,利落从采用的解决方案在这里:
只是覆盖all()形式要求内部方法

 class RegistrationRequest extends Request
  {

...

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

    if(isset($attributes['password']) && empty($attributes['password'])) 
        {
            unset($attributes['password']);
        }
    $this->replace($attributes);

    return parent::all();

}

...

}
Run Code Online (Sandbox Code Playgroud)

Bog*_*dan 5

要完成这项工作,您需要修改App\Http\Requests\Request类的内容以允许清理输入的方法(类代码取自Laracasts 帖子):

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

abstract class Request extends FormRequest
{
    /**
     * Validate the input.
     *
     * @param  \Illuminate\Validation\Factory  $factory
     * @return \Illuminate\Validation\Validator
     */
    public function validator($factory)
    {
        return $factory->make(
            $this->sanitizeInput(), $this->container->call([$this, 'rules']), $this->messages()
        );
    }

    /**
     * Sanitize the input.
     *
     * @return array
     */
    protected function sanitizeInput()
    {
        if (method_exists($this, 'sanitize'))
        {
            return $this->container->call([$this, 'sanitize']);
        }

        return $this->all();
    }
}
Run Code Online (Sandbox Code Playgroud)

之后,您只需要sanitizeUpdateUserRequest类中编写 add方法,password当它为空时从输入中删除该字段:

public function sanitize()
{
    if (empty($this->get('password'))) {
        // Get all input
        $input = $this->all();
        // Remove the password field
        unset($input['password']);
        // Replace the input with the modified one
        $this->replace($input);
    }

    return $this->all();
}
Run Code Online (Sandbox Code Playgroud)

现在使用sometimes密码字段的规则将起作用:

public function rules()
{
    return [
        // Other rules go here
        'password' => 'sometimes|required|confirmed'
    ];
}
Run Code Online (Sandbox Code Playgroud)