skip to Main Content

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


  1. Create new query builder for each variable because query builder is mutable

    This should work

    $availableSpecializations = Specialization::query()->pluck('name')->toArray();
    
    $specDoesntExist = Specialization::query()->where('id', $spec)->doesntExist();
    
    $existedSpecIds = Specialization::query()->whereIn('name', $existed)->get();
    
    Login or Signup to reply.
  2. The issue arises from the fact that you’re modifying the same query builder:

    $preparedSpec = Specialization::query();
    

    instance multiple times, which accumulates all the modifications and affects subsequent calls

    Try this Instead:

    // Initial Query
    $preparedSpec = Specialization::query();
    
    // First Call
    $availableSpecializations = (clone $preparedSpec)->pluck('name')->toArray();
    
    // Second Call
    $specDoesntExist = (clone $preparedSpec)->where('id', $spec)->doesntExist();
    
    // Third Call
    $existedSpecIds = (clone $preparedSpec)->whereIn('name', $existed)->get();
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search