Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

khanimranm's avatar

Variable used for joining conditional query scope is getting overwritten

The two dd($resourceSchedule->count() ) results give different values. I need the $resourceSchedule variable to remain unchanged in order to build the conditional query.

    protected function getResourceItemSchedule($resourceItemId)
    {
      $resourceType = Str::singular(request()->segments()[0]);

      if($resourceType == 'location') $resourceSchedule = Schedule::locationSchedule($resourceItemId);

      if($resourceType == 'service') $resourceSchedule = Schedule::serviceSchedule($resourceItemId);

      if($resourceType == 'provider') $resourceSchedule = Schedule::providerSchedule($resourceItemId);

// dd($resourceSchedule->count() shows 1);
      $resourceItemSchedule = $resourceSchedule->current()->endDateNull()
        ->latest('end_date');
// dd($resourceSchedule->count() shows 0);
      if ($resourceItemSchedule->count() == 0 ) {
        $resourceItemSchedule = $resourceSchedule->current()->endDateNotNull()
        ->latest('end_date');
      }

      if ($resourceItemSchedule->count() == 0 ) {
        $resourceItemSchedule = $resourceSchedule->next()->endDateNull()
        ->oldest('start_date');
        dump($resourceSchedule->count());
        dd($resourceItemSchedule->count());
      }

      if ($resourceItemSchedule->count() == 0 ) {
        $resourceItemSchedule = $resourceSchedule->next()->endDateNotNull()
        ->oldest('start_date');
      }

      return $resourceItemSchedule->first();
    }

0 likes
2 replies
frankincredible's avatar

The reason why your first dd() is 1, and the second is 0, is because on your first one, you hadn't chained on -> endDateNull() yet for the first dd(), but the second one includes that in the where clause.

The query Builder chains anything you add to it, even if it's in a separate statement.

khanimranm's avatar

Fine enough. Is there any workaround for this chaining issue here. Otherwise instead of One function getResourceItemSchedule, I may have to create three functions for location, service, and provider. Most of these will be repetitive code.

Please or to participate in this conversation.