I have a variable that contains a model and I want to duplicate it with all its criteria to another variable.
$modelOne = ModelOne::where('column_one', 'value_one');
if($condition_one) {
$modelOne = $modelOne->where('column_two', 'value_two');
}
... and many other if conditions ...
$modelTwo = $modelOne;
The problem starts from here that when I add another where
to $modelTwo
, the $modelOne
is affected either.
for example when I do $modelTwo->where('specific_column', 'specific_value')
, the $modelOne
will be limited by the where
set for $modelTwo
.
How can I separate their where
s?
You can use the PHP clone
keyword:
$modelOne = ModelOne::where('column_one', 'value_one');
// ...
$modelTwo = clone $modelOne;
// changes to $modelTwo should not affect $modelOne anymore
The eloquent builder internally implements the __clone
magic method to also clone the internal query builder