laravel : sanitize request data before validation
To make this work you'll need to modify the contents of the App\Http\Requests\Request
class to allow a way to sanitize the input (class code taken from 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();
}
}
After that you just need to write add sanitize
method in the UpdateUserRequest
class that removes the password
field from the input when it's empty:
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();
}
Now using the sometimes
rule for the password field will work:
public function rules()
{
return [
// Other rules go here
'password' => 'sometimes|required|confirmed'
];
}