Home » Php » laravel – PHP: update fields ONLY if replacement is present. If not, remain untouched

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

Posted by: admin February 25, 2020 Leave a comment

Questions:

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.

How to&Answers:

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);

Answer:

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);
}

Answer:

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);