jake2025's avatar

Laravel 5 : Filtering built-in paginator

Greetings pros,

i have watched pagination tutorial by sir jeffrey but i was wondering how can i send the append request on the query and filter the result.

Thank you in advance!

0 likes
6 replies
mgsmus's avatar

Do you mean this:

{!! $users->appends(['sort' => 'votes'])->render() !!}

?

jake2025's avatar

Sorry i was not specific. Like for example. I want to filter the results by user input:

{!! $activities->appends(Request::except('page'))->render() !!}

and if the Request is :

user_id = 1

The result should be filtered to user_id = 1

martinbean's avatar

@jake2025 You need to apply the filter in your controller action:

$activities = new Activity;

if ($request->has('user_id')) {
    $activities = $activities->where('user_id', '=', $request->get('user_id'));
}

// And so on

$activities = $activities->paginate();

return view('activities.index', compact('activities'));

This will then only paginate the matching records.

jake2025's avatar

Last question pros how can i append the request on the url like what sir jeffrey did on the video, Like after he clicks the intermediate and the difficulty was appended on the url with the input.

namik-mesic's avatar
Level 3

@jake2025

There are two ways to go around it.

First of all, if something simple is needed, this would do:

<a href="{{ url('something') . '?filterKey=filterValue' }}">My Filter</a>

You could then use the filterKey variable in your controller via

$filter = Input::get('filterKey') // or using a Request instance

if ($filter !== null)
{
    // do something with my eloquent query builder that might involve the key
    $model->where('someImportantFilter', '=', $filter); // like this
}

Of course this is just a very simple example.

You could also do this via a form that submits a GET request, and have a dedicated filter class or repository handle your Input::all() or Input::only() data from the form if the filtering gets more complex.

charlieBrown's avatar

@namik-mesic If you click twice at the same link it will add the filter twice to the URL. Any way around it?

Please or to participate in this conversation.