Save vs update in laravel

Added on Wed, 21 Aug 2019

These methods both allow you to save data into database.

The save() method perfroms as INSERT when you create a new model which is currently is not presented in your database table:

$flight = new Flight;

$flight->name = $request->name;

$flight->save(); // it will INSERT a new record
Also it can act like an UPDATE, when your model already exists in the database. So you can get the model, modify some properties and then save() it, actually performing db's UDPATE:

$flight = App\Flight::find(1);

$flight->name = 'New Flight Name';

$flight->save(); //this will UPDATE the record with id=1
An update() method allows you to update your models in more convenient way:

App\Flight::where('active', 1)
->where('destination', 'San Diego')
->update(['delayed' => 1]); // this will also update the record
So you even shouldn't assign a retrieved model to any variable. Updated properties are passed as arguments.

Examples and more info in the Laravel's docs.

Write a reply

Replied by: General on 2019-08-21 13:40:06

How about concurrency issues while insert/update. It's worth to create a reasonable write interface and handle duplications