I don't know what is wrong with my query, but the count is clearly wrong, it kept showing as 1912 when my total records are 12363
to change this line under my default case
$q = Visitor::where('created_at', '<', now());
to
$q = Visitor::all(); but I got error;
Method Illuminate\Database\Eloquent\Collection::orderBy does not exist.
switch ($interval) {
case 'day':
$q = Visitor::where('created_at', '>', now()->today());
break;
case 'week':
$q = Visitor::where('created_at', '>', now()->subWeek());
break;
case 'month':
$q = Visitor::where('created_at', '>', now()->subMonth());
break;
case 'year':
$q = Visitor::where('created_at', '>', now()->subYear());
break;
case 'last':
$q = Visitor::where('created_at', '>', $last);
break;
default:
$q = Visitor::where('created_at', '<', now());
break;
}
$visitors = $q->orderBy('created_at', 'desc')->paginate(15);
http://app.test/visitor?interval=year
I got 1912 - correct 👍🏽
I got 1912 - not correct ❌, It should query all since the interval is not specified.
If I do :
dd(count(Visitor::all()));
I got 12363 so that should be the right value.
$q = Visitor::all(); returns a Illuminate\Database\Eloquent\Collection.
Calling $visitors = $q->orderBy('created_at', 'desc')->paginate(15); will call ->orderBy(...) on an Eloquent Collection of which that method doesn't exist in that class.
Instead of:
$q = Visitor::where('created_at', '<', now()); ❌
Use this:
$q = Visitor::query(); ✅
Maybe you can use ->whereDate('created_at', now()), with ->whereTime('created_at', '00:00:00') if you need