What is the difference between save() and update() method in Laravel.
I have used save() method in case of update query but in few cases it acts as update and in few case it act as insert query function. Please let me know what exactly the difference between them.
These methods both allow you to save data to a database. So you don't even need to assign the retrieved model to any variable. Updated properties are passed as arguments. Examples and more info in the Laravel's docs.
In short save() method is used both for saving new model, and updating existing one. here you are creating new model or find existing one, setting its properties one by one and finally saves in database, while in create method you are passing array, setting properties in model and persists in database in one shot.
save() method is used both for saving new model, and updating existing one. here you are creating new model or find existing one, setting its properties one by one and finally saves in database.
Laravel - Update Records Advertisements. We can update the records using the DB facade with update method. The syntax of update method is as shown in the following table. Syntax. int update(string $query, array $bindings = array())
These methods both allow you to save data to a database.
The save()
method performs an INSERT
when you create a new model which is currently is not present 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
Theupdate()
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 don't even need to assign the retrieved model to any variable. Updated properties are passed as arguments.
Examples and more info in the Laravel's docs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With