Latest news about Bitcoin and all cryptocurrencies. Your daily crypto news habit.
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.
Paginatable Trait
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.
Dynamic (but limited) Page Size with Laravel Pagination was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.
Disclaimer
The views and opinions expressed in this article are solely those of the authors and do not reflect the views of Bitcoin Insider. Every investment and trading move involves risk - this is especially true for cryptocurrencies given their volatility. We strongly advise our readers to conduct their own research when making a decision.