Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Model::create or Model->save()

Tags:

php

laravel

I'm wondering what approach should I use for storing data in the database;

First approach

$product = Product::create($request->all());

In my Product model I have my $filable array for mass assigment

Second approach

    $product = new Product();
    $product->title = $request->title;
    $product->category = $request->category;
    $product->save();

Is any of these two "Better solution"? What should I generally use?

Thank you for you advice

like image 932
user13746 Avatar asked Nov 27 '14 16:11

user13746


People also ask

What is difference between create and save in Laravel?

What is difference between create and save in Laravel? Save can be used to both create a new Record and update a existing record . Whereas create is used to create a new record by providing all required field at one time .

How do I save a model in Laravel?

To quietly save a model in Laravel you can make use of the "saveQuietly" method available to each model instance. ->saveQuietly();

What does Laravel save () return?

This code will never execute what's within the catch block, since the save() method returns false, therefore it does not trigger an exception.

How we can create model in Laravel?

You can use the artisan make:model command line helper to generate new models for your application. To create a new Eloquent model for your links table, run: docker-compose exec app php artisan make:model Link.


1 Answers

Personal preference.

Model::create() relies on mass assignment which allows you to quickly dump data into a model, it works nicely hand-in-hand with validation rather than having to set each of the model properties manually. I've more recently started using this method over the latter and can say its a lot nicer and quicker.

Don't forget you also have a range of other mass assignment functions create(), update() and fill() (Possibly more).

like image 77
Wader Avatar answered Sep 22 '22 09:09

Wader