Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save vs update in laravel

Tags:

laravel-5

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.

like image 507
Pardeep Pathania Avatar asked Apr 27 '16 07:04

Pardeep Pathania


People also ask

What is the difference between save and update in laravel?

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.

What is Save () in laravel?

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.

What is difference between create and save in laravel?

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.

What is update in laravel?

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())


1 Answers

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.

like image 108
Gino Pane Avatar answered Oct 07 '22 17:10

Gino Pane