problem with this is withCount() not changing after when() is applied for example without when() transaction_count is 5000 and after when is applied it still remains 5000 ? it should change according to filter apply in when()
public function allUsers(Request $request)
{
$date = $request->input('date');
$location = $request->input('location');
$users = User::when(!empty($date), function ($query) use ($date) {
return $query->whereRelation('transactions', 'date', '=', date('Y-m-d', strtotime($date)));
})->when($location, function ($query) use ($location) {
return $query->whereRelation('transactions', 'location', '=', $location);
})->withCount(['transactions'])->get();
return response()->json($users);
}
2
Answers
You need to place your withCount function inside the closure of when function, then only it will count the data based on your condition, else it will always return the whole transaction_count of 5000,
you need to change your query something like below.
From what I remember,
whereRelation()
executes a second query, separately, andwithCount()
executes a subquery within the same one.Instead of
whereRelation()
, try to usejoin()
Instead of:
Try: