Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kkatwork's avatar

How to filter paginated results?

I have an application where I need to filter further the paginated results. When I apply filter method after the pagination method the view gives an error.

I can't insert the logic in sql query because it is complex enough.

How can I paginate and filter the results and pass to view so that pagination also works from there?

Any help appreciated.

0 likes
6 replies
aurawindsurfing's avatar

You should apply filter before paginating results. Think of pagination as a view. First you get data then you pass it to the view.

kkatwork's avatar

@aurawindsurfing Thanks for the reply.

I am trying to do such thing.

$items = $items->paginate(10);
$filtered = $items->filter( function($item) {
            if (condition) {
                return true;
            }
  }); 

Now I want to show the filtered items in view but with pagination links. I hope you got my point. Please reply.

automica's avatar

@kkatwork do paginate last

$items = Model::all();

$items = $items->filter( function($item) {
            if (condition) {
                return true;
            }
  }); 
return $items->paginate(10);

if you filter after your paginate, you wont have the right number of results per page as you'll be removing some of them with your filter.

kkatwork's avatar

@automica Thanks for reply.

I tried that. But I get error - 'paginate' does not exist. I think it is because after filtering we get a collection and paginate does not exist on collection.

Snapey's avatar

You must apply filter to your DB/Eloquent query. Don't try to do it on the collection.

2 likes
kkatwork's avatar

@snapey Thanks for the reply.

I have a little complex condition. When I do it by chaining where method on eloquent I get not a number and various other errors. Can you guide me how should I do this operation please?

where(function($query){
            $query->where(((int)'items' - (int)'checked_items') - 'other_item', '>', 3);
        })

Please or to participate in this conversation.