I need to know what is the difference of save()
and create()
function in laravel 5. Where we can use save()
and create()
?
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.
create() is a function from Eloquent, insert() - Query Builder. In other words, create is just an Eloquent model function that handles the creation of the object to the DB (in a more abstract way). Insert however tries to create the actual query string.
It looks like save() method only works on objects. Eloquent only deals with objects (models) and performs database inserts and updates to persist those models. $model = new Model; $model->fill(array); $model->save(); new up an empty model(object) then fill it with your array of data, and finally save it.
Laravel Model::create or Model->save()$product = new Product(); $product->title = $request->title; $product->category = $request->category; $product->save();
Model::create
is a simple wrapper around $model = new MyModel(); $model->save()
See the implementation
/** * Save a new model and return the instance. * * @param array $attributes * @return static */ public static function create(array $attributes = []) { $model = new static($attributes); $model->save(); return $model; }
save()
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.
save() accepts a full Eloquent model instance
$comment = new App\Comment(['message' => 'A new comment.']); $post = App\Post::find(1); $post->comments()->save($comment);
create()
create() accepts a plain PHP array
$post = App\Post::find(1); $comment = $post->comments()->create([ 'message' => 'A new comment.', ]);
EDIT
As @PawelMysior pointed out, before using the create method, be sure to mark columns whose values are safe to set via mass-assignment (such as name, birth_date, and so on.), we need to update our Eloquent models by providing a new property called $fillable. This is simply an array containing the names of the attributes that are safe to set via mass assignment:
example:-
class Country extends Model { protected $fillable = [ 'name', 'area', 'language', ]; }
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