andcl
andcl

Reputation: 3548

PHP: update fields ONLY if replacement is present. If not, remain untouched

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

Answers (3)

Paulo Moreira
Paulo Moreira

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

Erich
Erich

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

Jerodev
Jerodev

Reputation: 33196

You can use the get() method on the request and pass the current value as the default value.

$user->name = $request->get('name', $user->name);

Upvotes: 3

Related Questions