Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
97 views
in Technique[技术] by (71.8m points)

Save vs update in laravel

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.

question from:https://stackoverflow.com/questions/36883728/save-vs-update-in-laravel

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 = AppFlight::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:

AppFlight::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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...