Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Quick tip - Using lightweight pagination in Laravel

If you want to paginate database records in Laravel, you can use the paginate method on the query builder or an Eloquent query.

So, for instance, if you want to paginate a query on the users table for five records per page, you can use the paginate method like so.

$users = DB::table('users')->paginate(5);

Here’s what you get if you dd()‘d the output.

As you can tell, it has several parameters such as total (total number of records), lastPage, currentPage, and so on that you can use this information to show the pagination links.

But here, if you notice, paginate() gives the count of a total number of records the query returns and that is a problem. This operation is sort of expensive if you’re paginating a large set of records. So, unless you need the total number of records and number of pages, you should use something else. Something way more light-weight.

Enter simplePaginate().

Light-weight pagination with simplePaginate()

As I mentioned, in the scenarios where you don’t need the total number of records and number of pages, you can use the simplePaginate().

What this method do differently than paginate() is, it doesn’t count the number of records and a total number of pages the query returns. And because of that, you can optimize at the pagination front.

So, if we want to re-write the previous query using simplePaginate(), you can do it like so.

$users = DB::table('users')->simplePaginate(5);

Here’s what you get if you dd()‘d the output.

As you can tell, the returned object is stripped down with only necessary parameters such as hasMore (which indicates that there are records available on the next page) and currentPage.

Usecases

This kind of approach is especially useful when you want to implement the infinite scrolling where you don’t really need the total number of records or how many pages are there.

Or in the scenario where you just need to show the “next” and “previous” links leaving out showing the link of each page.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?