'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



Solution 1:[1]

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();

Solution 2:[2]

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.

Solution 3:[3]

Yes, it is possible different ways: you can use the mass assignment without saving.

Please remember to set first the $fillable property in your model.

WAY #1: using the method fill

$model = new YourModel;

$model->fill([
    'field' => 'value',
    'another_field' => 'another_value'
]);

$model->save();

WAY #2: using the constructor

$model = new YourModel([
    'field' => 'value',
    'another_field' => 'another_value'
]);

$model->save();

Laravel documentation: https://laravel.com/docs/8.x/eloquent

Solution 4:[4]

there is also a method you can call it statically to get new instance:

 $modelInstance =   $modelName::newModelInstance();

it takes array $attributes = [] as a parameter

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joseph Silber
Solution 2 Kris Tremblay
Solution 3
Solution 4 OMR