Using Laravel's Pagination Class with JQuery Masonry and Infinite Scroll

25th July 2012

Just a quick one, but it's something that I got stuck with for a while.

If you try and use Laravel's pagination class with JQuery Masonry along with Infinite Scroll, you may find a problem. When you scroll down beyond what should be the last page, you'll probably find that you keep getting the last page over and and over again, causing genuinely infinite scrolling. The reason for this took me some uncovering.

When Inifinite Scroll requests an additional page, it increments the page number, but gets the same content back - however, there is no reason why it should know that that's the case. It's because it keeps getting new content back that it keeps trying, but the issue is actually in the Laravel Paginator.

In order for Infinite Scroll to know when to stop, it expects a page not found; i.e., a 404. However when the Pagination class gets a page number from the GET parameters which is greater than the maximum page number, it simply sets it to the last available page, and returns that content. It's by no means a bug; just different behaviour to that which Infinite Scroll expects.

There are a couple of ways around it. You could simply override the Paginator class and change the behaviour. Or, in your controller / route you could simply intercept the results from the paginator and do a return Response::error(404), I guess it depends on the case.