Stop Repeating if Checks with Laravel whenHas()
When processing API requests, you often need to check whether a field was actually included before doing something with it.
A common approach looks like this:
if ($request->has('avatar')) {
$user->update([
'avatar' => $request->avatar,
]);
}
Laravel provides a cleaner way to express the same intention.
Use whenHas()
$request->whenHas('avatar', function ($avatar) use ($user) {
$user->update([
'avatar' => $avatar,
]);
});
The callback is executed only when the avatar field is present in the request.
This can make request-processing code easier to read when you have several optional fields.
A Practical Example
Imagine an admin API where different profile fields are optional:
$request->whenHas('name', function ($name) use ($user) {
$user->name = $name;
});
$request->whenHas('email', function ($email) use ($user) {
$user->email = $email;
});
$request->whenHas('bio', function ($bio) use ($user) {
$user->bio = $bio;
});
$user->save();
Instead of writing multiple if ($request->has(...)) blocks, the intention is directly expressed through whenHas().
whenHas() vs whenFilled()
There is an important difference.
whenHas() checks whether the input exists:
$request->whenHas('bio', function ($bio) {
// Runs when bio exists in the request.
});
While whenFilled() runs only when the input exists and isn't empty:
$request->whenFilled('bio', function ($bio) {
// Runs when bio has a non-empty value.
});
This distinction is useful when an empty value has a different meaning from a missing field.