Laravel makes pagination an extremely simple process, you simply call paginate()
on Eloquent and be done with it. Today I received a feature request where I had to allow the front-end team to decide the size of the page. It’s also a simple task, you just give it as a parameter paginate($size);
. Something like this:
Sometimes this is all you need because your business model can tell you if that entity might grow indefinitely. For this case, we charge per user and it’s very unlikely that a company will be buying 1 million users. However, I know that in the next few weeks I’ll be working on some other APIs that do have millions of records, which means I cannot allow a page size bigger than a reasonable amount.
Great. Now I can make sure that the API I’m exposing on the internet will not degrade our services if someone set page_size
to 1 billion. But it still doesn’t feel awesome because I have to remember to set this up every time I’m writing a paginatable endpoint.
Behind the scenes, Laravel defaults to getPerPage
on the Eloquent Model in case a specific page size is not provided. By default, Laravel ships with 15
per page. With a paginatable trait, we can override that method and implement it on models that should allow the Requester to tell us how many items per page they want while validating if they’re not requesting too much.
Just use the trait on your model and the Controller
can be a slim paginate()
call. It’s a really simple and small thing, but quite powerful and convenient if you’re expecting to write these kind of public APIs.