Search code examples
phplaravelmodeleloquent

Different way of Model object creation in laravel


There are following ways in which we can create model objects in controller and insert records to database.

First Approach

$object1 = new Model;
$object1->column = $val;

... 
...

$object1->save();

Second Approach

$object2 = new Model();
$object2->column = $val;

... 
...

$object2->save();

Both of these work without any problem. I have checked and searched on Internet. But, I don't understand that these two way are exactly same or something else.

And another thing is if I just want to save records to a database table which one is correct and best practice ?

Can anyone describe ?

Thanks,


Solution

  • I found this post on stackoverflow : Instantiate a class with or without parentheses?

    Here is a part of the answer :

    While both ways are fine, I personally would prefer using new Car(); because usually, a method is being called here, and function/method calls in PHP require (). Also, it's more consistent with instantiations that have parameters.

    So there is no negligible differences between those two approaches. So choose the one that is the most relevant to you. But keep using the same approach !