Dec 15, 2022
11
Level 1
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?
Level 75
Please or to participate in this conversation.