Laravel: sanitize request data before validation

There is a form request UpdateUserRequestthat checks the value of a field against its rules defined in rulesmathod. It has rules () and authorize () methods by default. I want to prevent checking and updating empty fields (e.g. password).

using sometimesin the rules is not useful, since html entries will be present in the POST request, even if they are empty.

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

]

so I have to remove the empty keys of the POST request before using sometimesin the rules.
Q: where is the best place to clear the Request array?
Is there any way to create laravel to handle such situations?

P.S: :
@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();

}

...

}
+4
2

, App\Http\Requests\Request, ( , 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();
    }
}

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

sometimes :

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

, .

$id, , . , name email , , - name email , , 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();
    }
0

Source: https://habr.com/ru/post/1629946/


All Articles