Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you create a new Model instance without saving it to the database

I want to create a whole bunch of instances of a model object in Laravel, then pick the optimal instance and save it to the database. I know that I can create an instance with Model::create([]), but that saves to the database. If possible I'd like to create a bunch of models, then only "create" the one that is best.

Is this possible?

I am using Laravel 5.0

like image 469
ajon Avatar asked Aug 25 '15 00:08

ajon


People also ask

How do I create an instance of a model?

To create a new instance of a model, instantiate it like any other Python class: class Model (**kwargs) The keyword arguments are the names of the fields you've defined on your model. Note that instantiating a model in no way touches your database; for that, you need to save() .

What is hydrate in laravel?

Laravel Core Adventures - Did you know? Ever wondered what "hydrate" means? I've been there. Then I realized it's just a fancy word for filling an object with data. In this Eloquent Builder example, Laravel fills a new collection object with models from an array.


2 Answers

You create a new model simply by instantiating it:

$model = new Model; 

You can then save it to the database at a later stage:

$model->save(); 
like image 121
Joseph Silber Avatar answered Oct 14 '22 00:10

Joseph Silber


You can create instances with Model::make(). It works the same way as create but it doesn't save it.

Whether or not this is best practice is another matter entirely.

like image 20
Kris Tremblay Avatar answered Oct 13 '22 23:10

Kris Tremblay