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

时间:2016-02-22 20:18:11

标签: validation laravel request rules

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

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

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

]

所以我应该在规则中使用sometimes之前删除POST请求的空键 问题是:清除Request数组的最佳位置在哪里?
是否有任何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();

}

...

}

2 个答案:

答案 0 :(得分:3)

要完成这项工作,您需要修改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(); } } 类的内容以允许一种方法来清理输入(从this Laracasts post获取的类代码):

sanitize

之后,您只需在UpdateUserRequest类中编写添加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(); } 字段中删除{<1}}字段:

sometimes

现在使用密码字段的public function rules() { return [ // Other rules go here 'password' => 'sometimes|required|confirmed' ]; } 规则将起作用:

php artisan schedule:run

答案 1 :(得分:0)

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

我根据传递的$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();
    }
相关问题