0
votes

I am parsing through the Laravel request object to identify if any inputs were entered by the user, so that I may update the model with only the updated values.

Currently I am using:

if (isset($request->$field) && $request->$field != $model->$field) {
     $model->$field = $request->$field;
}

and I recently found a Laravel request method whenHas that seems to be a more efficient way to accomplish this task.

I searched the web and stackoverflow for examples but only found the basic construct. I am new to OOP but do understand this would be related to closures/callbacks.

FYI, in my current code I have the isset() function since the response may contain a null value for the field that I am comparing against the model's related field value (my current code snippet is within a "foreach($fields as $field) function).

How would I accomplish this functionality with the whenHas method?

Any help would be appreciated, thank you!

2

2 Answers

1
votes
$request->whenHas($field, function ($value) use ($field, $model) {
    $model->$field = $value;
});

// or PHP 7.4+

$request->whenHas($field, fn ($value) => $model->$field = $value);

If the request has the field the value of that input will be passed to your callback. This method does return the $request if the field does not exist, or it will return the $request or anything you return from the callback if it runs it (the field exists).

Though you may not really have to be doing this at all. If you have specific fields to check for you could iterate through $request->only($fields).

0
votes

The basic problem I was experiencing is that validation would fail for unique fields when a user was 'updating' their model. I attempted to address this by the 'whenHas()' method when there was a much simpler solution... simply adding the current user's info to the validation rule (e.g. 'email' => 'unique:table,email_column_to_check,id_to_ignore').