Eloquent update and get record back Eloquent update and get record back laravel laravel

Eloquent update and get record back


This will solve the problem

$product = Product::where('id','76887')->first();$result = $product->update(['field' => 'value');$theUpdatedData = $product->refresh(); return $theUpdatedData //This return the updated record 


IMHO your way is arguably the most efficient with Eloquent.

If you care about performance more than using Eloquent then with raw queries in PostgreSQL (with RETURNING clause) or SQL Server (with OUTPUT clause) you can return updated records in one go.

MySQL unfortunately doesn't have such support on a statement level.

In all supported by Laravel databases you can also achieve this (one trip to the database) also with a stored procedure.


If you want the most efficient method possible, you can update the database with the single update command, and then loop through your $objects in memory with a foreach loop and set each $object->field = 'value'. It isn't especially elegant, but that would be the most efficient way to do it in terms of speed since that way you don't need to re-fetch the models from the database.

$result = MyObject::where(...)->update(['field' => 'value');foreach ($objects as $object) {   $object->field = 'value';}