no, not a singleton. You are just passing the same object around and changing its value. At no point do you have a second model.
May 28, 2024
3
Level 1
Are Models singletons in Laravel?
I came across an unexpected / unknown behavior today and maybe it's been there all along and I literally didn't know. It appears that any kind of Model instance is a singleton. Is that correct? It's interesting to know and understand. I've been using Laravel for about 6 years now, code with it regularly and never came across a situation that this came to light.
I've tested a couple ways of making a Model and they all come back as singletons.
Is there a way around this if needed?
Below are a few test code blocks to illustrate.
public function index(Request $request)
{
$p = (new Project)->make(['name' => 'New Project']);
dump($p->name); // Returns 'New Project'.
$new_p = $this->something($p);
dump($new_p->name); //Returns 'something different'.
dd($p->name); // Returns 'something different' also.
}
public function something($project)
{
$project->name = 'something different';
return $project;
}
public function index(Request $request)
{
$p = Project::make(['name' => 'New Project']);
dump($p->name); // Returns 'New Project'.
$new_p = $this->something($p);
dump($new_p->name); //Returns 'something different'.
dd($p->name); // Returns 'something different' also.
}
public function something($project)
{
$project->name = 'something different';
return $project;
}
public function index(Request $request)
{
$p = Project::make(['name' => 'New Project']);
dump($p->name); // Returns 'New Project'.
$this->something($p); // NOT assigning a new var reference
dd($p->name); // Returns 'something different' also.
}
public function something($project)
{
$project->name = 'something different';
}
public function index(Request $request)
{
$p = Project::find(1);
dump($p->name); // Returns 'New Project' from database.
$new_p = $this->something($p);
dump($new_p->name); //Returns 'something different'.
dd($p->name); // Returns 'something different' also.
}
public function something($project)
{
$project->name = 'something different';
return $project;
}
Please or to participate in this conversation.