1

What is the best way to update my object in the database from my request?

Currently I am updating every single field and then saving the object:

$user = User::findOrFail($id);
$user->username = $request->username;
$user->role = $request->role;
$user -> save();

Also it is not required to have all the fields present. One request can update the role of the user, but other can update only the username.

How can I loop and update only the present fields from the request or is there a way to pass the whole request as a paramater and setting only the id and eloquent to know what to do with it?

1 Answer 1

2

You could simply do a foreach() over the values in $request and assign them to your $user prior to saving:

$user = User::findOrFail($id);
foreach($request->except(["_token"]) AS $key => $value){
  $user->{$key} = $value;
  // Example: $key = "username", $value = "BobSmith"; `$user->username = "BobSmith";`
}
$user->save();

Note: Use $request->except() to omit fields that are sent in the request but don't exist as columns on the users table, like _token (required in POST requests).

Sign up to request clarification or add additional context in comments.

4 Comments

That worked thanks, but I am including a token with the header and i removed the except, but foreach($request as $key => $value) didn't work. It gave Object of class .. could not be converted to string. Any ideas why?
Oh I included $request->all() and it worked is this the right way?
One of your inputs (inside of $value) can't be converted to a string; might need a check while looping.
@ivaylo Yes, its because $request is an object. But function $request->all() or $request->except(here array of exception) or $request->only(here array of fields) returns array of data with you can put in forach loop. If you have $fillable property in your User object you could achieve same thing by doing this: User::findOrFail($id)->update($request->only(['username','role']);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.