Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

php - How to use Laravel $request->whenHas() method?

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!

question from:https://stackoverflow.com/questions/65867319/how-to-use-laravel-request-whenhas-method

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
$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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...