Conditional Query & Pagination in Laravel 7

  eloquent, laravel, laravel-7, pagination, php

$vistors will return all data from vistors table

I’m hoping to query all visitors if $visitor->ip != '127.0.0.1' when $inputs['hideMe'] == true requested from the client-side.

Route

Route::get('/visitor','[email protected]');

I have

switch ($interval) {
    case 'day':
    $data = Visitor::where('created_at', '>', now()->today())->paginate(15);
    break;
    case 'week':
    $data = Visitor::where('created_at', '>', now()->subWeek())->paginate(15);
    break;
    case 'month':
    $data = Visitor::where('created_at', '>', now()->subMonth())->paginate(15);
    break;
    case 'year':
    $data = Visitor::where('created_at', '>', now()->subYear())->paginate(15);
    break;
    default:
    $data = Visitor::orderBy('updated_at', 'desc')->paginate(15);
    break;
}




$visitors = [];
function hideMe($inputs, $data){

    foreach($data as $i => $visitor){
        if($visitor->ip != '127.0.0.1'){
            $visitors[$i] = $visitor;
        }

    }

}

if(array_key_exists('hideMe', $inputs)){
    $hideMe  = $inputs['hideMe'];
    if($hideMe == true){
        hideMe($inputs, $data);
    }
} else {
    $visitors = $data;
}

When I did that, it does not seem to work.
Since I use paginate on my view, I will get this error all the time.

Call to a member function withQueryString() on array

Result

This is working perfectly

  • http://app.test/visitor?interval=day
  • http://app.test/visitor?interval=week
  • http://app.test/visitor?interval=month
  • http://app.test/visitor?interval=year

This is not working at all

  • http://app.test/visitor?interval=week&hideMe=true

Any suggestions for me on how to add some logic check to my query

Source: Laravel

Leave a Reply