Skip to content

Instantly share code, notes, and snippets.

@james2doyle
Created May 26, 2017 18:11
Show Gist options
  • Save james2doyle/a7d34dafda06b83733cac97d2940d355 to your computer and use it in GitHub Desktop.
Save james2doyle/a7d34dafda06b83733cac97d2940d355 to your computer and use it in GitHub Desktop.
Update a Laravel Eloquent model and return the fresh model
<?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();
@TsuiAnthonYVR
Copy link

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.

@james2doyle
Copy link
Author

Just checked the Laravel repo, and it seems like this was added in 5.4.20.

@ManojKiranA
Copy link

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