laravel : 在验证之前清理请求数据

laravel : sanitize request data before validation

有一个 UpdateUserRequest 表单请求根据 rules 方法中定义的规则验证字段值。它默认具有 rules() 和 authorize() 方法。我想防止验证和更新空字段(例如密码)。

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

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

]

所以我应该在规则中使用 sometimes 之前删除 POST 请求的空键。
问题是:清除请求数组的最佳位置在哪里?
是否有任何 laravel 内置方法来处理此类情况?

P.S :解决方法:
@Bogdon 解决方案仍然有效并且有效,但还有另一个简单、漂亮、整洁的解决方案采用了 here:
只需覆盖表单请求中的 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();

}

...

}

我不确定清除字段的最佳方式,但这是我目前在系统上处理用户更新的方式。

我根据通过的$id找到用户,然后更新相应的记录。我假设 nameemail 永远不会为空,只有密码可以为空 - 所以我们可以将 nameemail 字段设置为传入的值然后使用 if 语句检查 password 字段是否为空并相应地更新。

我使用的大致如下:

public function update($id)
    {
        $user = User::find($id);

        $user->name   = Input::get('name');
        $user->email      = Input::get('email');
        if (Input::get('password') != "")
        {
        $user->password   = Hash::make(Input::get('password'));
        }

        $user->save();
    }

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

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();
    }
}

之后,你只需要在 UpdateUserRequest class 中编写 add sanitize 方法,当 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();
}

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

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