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

iamripespoon's avatar

Trouble with Separating a Query into 2 Separate States

I'm building a query for a Leads report. So the person will select parameters in a form and eloquent builds it's query based on the forms values and the results page will obviously show the results. The trouble i am having is...

I have say a query, mine is split into different functions but for this example i'll put it into a simpler form.

This part will load all Leads within the search date and where the affiliate ID is 5 and display them on the results page.


$q = Lead::query();
$q = $q->whereBetween('created_at', [$start_date, $end_date]);
$q = $q->where('affiliate_id', 5);

Before it gets to the results page though i also want to count the amount of leads from this affiliate that have been sold, and not sold, so i can display them on the results page at the top. So i'm doing the following, but i don't want to filter the results by whether it was been sold or not. I just want to show the count.


$soldQuery = $q;
$soldQuery = $soldQuery->where('sold', 1);
$soldCount = $soldQuery->count();

However the second query, specifically the $soldQuery = $soldQuery->where('sold', 1); part is overwriting the first query. So the results page are only showing sold leads.

Please can anyone advise what i'm doing wrong or a better way of doing it?

0 likes
0 replies

Please or to participate in this conversation.