Created
May 26, 2017 18:11
-
-
Save james2doyle/a7d34dafda06b83733cac97d2940d355 to your computer and use it in GitHub Desktop.
Update a Laravel Eloquent model and return the fresh model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// find the model, update the model, give me the fresh model | |
$updatedUser = tap(User::find(1), function ($user) use ($data) { | |
return $user->update($data); | |
})->fresh(); |
Just checked the Laravel repo, and it seems like this was added in 5.4.20.
I am using laravel version 5.8.32
and tap(Model::findOrFail($modelId))->update($updateArray);
this works fine for me
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In 5.4 you can:
$updatedUser = tap(User::findOrFail(1))->update($data)->fresh();
It's so wrong, but it's so Zonda!
If you don't want it to throw an error, you can even do:
$updatedUser = User::updateOrCreate(['id' => 1], $data)->fresh();
->fresh()
is of course optional, but if you have some observers / save event handlers that modifies the model you'll want to be sure and fetch from DB.