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
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 .
To quietly save a model in Laravel you can make use of the "saveQuietly" method available to each model instance. ->saveQuietly();
This code will never execute what's within the catch block, since the save() method returns false, therefore it does not trigger an exception.
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.
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).
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