How do you only update validated inputs? Hi All,
Is it possible to validate your request without forcing Illuminate\Validation\ValidationException to be thrown?
public function store(Request $request)
{
$fields = $request->validate([
'name' => 'required',
'email' => 'required|email',
'telephone' => 'required',
]);
return tap(Auth::user(), function($user) use($fields){
$user->update($fields);
});
}
My tests are as follow:
public function testThatAValidEmailIsProvider()
{
$user = $this->signInJohn();
$this->post(route('profile.info'), [
'name' => 'Barry White',
'email' => 'not-an-email.com',
'telephone' => '07779 555111',
])->assertStatus(201);
$user = $user->fresh();
$this->assertEquals('Barry White', $user->name);
$this->assertEquals('[email protected] ', $user->email);
$this->assertEquals('07779 555111', $user->telephone);
}
You would want to create a custom function that will try and catch the validation, looping through one rule at a time. Something like below. (Completely untested but should work.)
// Add as a helper function somewhere...
function validated($request, $rules = [])
{
$data = [];
foreach($rules as $key => $rule) {
try {
$data = array_merge($data, $request->validate([$key => $rule]));
} catch(\Illuminate\Validation\ValidationException $e) {}
}
return $data;
}
// Usage
$fields = validated($request, [
'name' => 'required',
'email' => 'required|email',
'telephone' => 'required',
]);
dump($fields);
Oh right, so there is no "official" way to do this then - seems to me like people would want to do this a lot, I could be wrong tho.
Thanks for your help. :)
Please sign in or create an account to participate in this conversation.