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

wassy83's avatar

Preserve initial eloquent query for multiple counts

I have a model Disponibilita, I want to make different queries to count number of rows based on a particular status to populate a chart in my frontend. The code I use is the following:

        //This is common for all queries
        $count = Disponibilita::whereYear('departure_date', $year);

        // Start counting
        $totals = [

            "available" => $count->when($month, function ($query) use ($month) {
                $query->whereMonth('departure_date', $month);
            })->count(),

            "deleted" => $count->when($month, function ($query) use ($month) {
                $query->whereMonth('departure_date', $month);
            })->where('status','LIKE','844%')->count(),

            "sold" => $count->when($month, function ($query) use ($month) {
                $query->whereMonth('departure_date', $month);
            })->where('status','LIKE','833%')->count(),

            "expired" => $count->when($month, function ($query) use ($month) {
                $query->whereMonth('departure_date', $month);
            })->where('departure_date', "<", today()->startOfDay())->where('status','NOT LIKE','833%')->count(),

            "issued" => $count->when($month, function ($query) use ($month) {
                $query->whereMonth('departure_date', $month);
            })->whereNull('option_date')->where('status','NOT LIKE','844%')->count()
            
        ];

First count in the array "available" is good, all the others are incorrect, like the previous query is changing the results of the second one. To fix this I'm using an arrow function instead of a variable to declare the initial Query Like this

$count = fn() => Disponibilita::whereYear('departure_date', $year);

and then recalling each time count in this way

$count()-> // next query

But I think this is a wrong approach.. any suggestion on how to preserve the initial $count query?

0 likes
11 replies
wassy83's avatar

@MichalOravec very good, thank you, but can you please explain to me why this is happening? the inital declaration of $count without any executors return just a query builder right?

Sinnbeck's avatar

@wassy83 Objects are passed by reference.

example

$foo = new Foo;
$bar = $foo;
$foo->name = 'John';
echo $bar->name; //John
1 like
Sinnbeck's avatar

@wassy83 There is no such button. You mark a best answer, and the thread is set as solved

Please or to participate in this conversation.