I show code in the screenshot, because I want to show you guys my line 43
The actual code is here :
public function index()
{
$inputs = Request::all();
$interval = '';
if(array_key_exists('interval', $inputs)){
$interval = $inputs['interval'];
}
switch ($interval) {
case 'day':
$visitors = Visitor::where('created_at', '>', now()->today())->paginate(20);;
break;
case 'week':
$visitors = Visitor::where('created_at', '>', now()->subMonth())->paginate(20);;
break;
case 'month':
$visitors = Visitor::where('created_at', '>', now()->subMonth())->paginate(20);;
break;
case 'year':
$visitors = Visitor::where('created_at', '>', now()->subYear())->paginate(20);
break;
default:
$visitors = Visitor::orderBy('updated_at', 'desc')->paginate(20);
break;
}
return View::make('layouts.be.visitors.index', get_defined_vars());
}
I visit
http://app.test/visitor?interval=year
As you can see
Laravel Debugbar detected that I did 2 queries on line 43
Why 2 ? Is this expected ?
Can I improve this into 1 ?
Please advise


second query is run by
paginate()method.If you look at this pagination response from laravel official documentation you will see one field called
total. That's why that query runs to get total number of records:That
select count(*) as aggregate from visitors WHERE created_at > '2019-03-13 12:22:22query runs automatically.If you want to set it manually you have to use
LengthAwarePaginator.See here about
LengthAwarePaginator: https://github.com/laravel/ideas/issues/826EDIT:
Here is how you can optimize your code:
See more about
whenmethod here: https://laravel.com/docs/7.x/queries#conditional-clausesHope this helps