so i have a problem while accessing variable that contain class object as a value, if i call it multiple time, it will change result. here the example:
// declared on the first line
$preparedSpec = Specialization::query();
// call on another line like this
$availableSpecializations = $preparedSpec->pluck('name')->toArray();
// call it again under $availableSpecializations
$specDoesntExist = $preparedSpec->where('id', $spec)->doesntExist();
the problem exists when i do this:
$existedSpecIds = $preparedSpec->whereIn('name', $existed)->get();
expected result of variable $existedSpecIds
should return data collection, but return empty array []
i don’t realy understand why this happen, may be some expert can explain? thanks in advanced
sorry for bad english
i have already try to initiate new class instead reusing it on $preparedSpec
variable, and of course it works.
and actually i just curious why that happen.
2
Answers
Create new query builder for each variable because query builder is mutable
This should work
The issue arises from the fact that you’re modifying the same query builder:
instance multiple times, which accumulates all the modifications and affects subsequent calls
Try this Instead:
clone will help you create a separate copy of the $preparedSpec query builder for each operation. This ensures that each query remains unaffected by changes made in other queries.