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.

View

http://app.test/visitor?interval=day

enter image description here

Route

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

I have

public function index()
{
    $inputs    = Request::all();
    $interval  = '';

    if(array_key_exists('interval', $inputs)){
        $interval  = $inputs['interval'];
    }

    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' || $visitor->ip != '24.62.137.111'){
                $visitors[$i] = $visitor;
            }

        }

    }

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


    // dd($visitors);


    return View::make('layouts.be.visitors.index', get_defined_vars());
}

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 on how to add logic to my query?

Source: Ask PHP

LEAVE A COMMENT