Reputation: 3548
I think it is a classical one, but in one of my Laravel controllers, I need to update the value of some fields ONLY if the corresponding replacement values are present in the incoming request. If they are not present, the must stay untouched. My "smartest" try so far:
$user->name = $request->name ?: $user->name;
$user->email = $request->email ?: $user->email;
...
Is there a smarter way of doing this using latest PHP or Laravel enhancements? Thanks in advance.
Upvotes: 2
Views: 621
Reputation: 56
You can also use a ternary operator and just check if the $request->name isen't null or empty.
Like so:
$user->name = (($request->name === NULL) ? $user->name : $request->name);
Upvotes: 0
Reputation: 2616
Typically in a Laravel controller update
method, you are passing the entire model attribute array through in the $request
. Your worry is that an empty/null value present in this array would automatically update the database column to null.
Not to worry, the sometimes
validation rule is your friend.
public function update(Request $request, Model $model)
{
$validated = $request->validate([
'name' => 'sometimes|string',
'email' => 'sometimes|email',
// ...
]);
$model->update($validated);
}
Upvotes: 0