How to Use Paginate in Eloquent for Laravel Pagination
Use the
paginate() method on an Eloquent query to split results into pages automatically. For example, User::paginate(10) returns 10 users per page with built-in navigation data.Syntax
The paginate() method is called on an Eloquent query builder instance. It accepts one argument: the number of items per page.
Model::paginate(perPage)- returns a paginator withperPageitems.- The paginator includes data like current page, total pages, and links for navigation.
php
User::paginate(15);Example
This example fetches 5 users per page and shows how to display them in a Blade view with pagination links.
php
<?php // Controller method public function index() { $users = User::paginate(5); return view('users.index', ['users' => $users]); } // Blade view (resources/views/users/index.blade.php) @foreach ($users as $user) <p>{{ $user->name }}</p> @endforeach {{ $users->links() }}
Output
<p>List of 5 user names displayed</p><nav>Pagination links for pages</nav>
Common Pitfalls
- Forgetting to call
links()in the Blade view, so no navigation links appear. - Using
get()instead ofpaginate()which returns all results without pagination. - Not passing the correct number of items per page or passing zero.
- Mixing
paginate()withskip()ortake()which can cause unexpected results.
php
<?php // Wrong: returns all users without pagination $users = User::get(); // Right: returns 10 users per page $users = User::paginate(10);
Quick Reference
| Method | Description |
|---|---|
| paginate(perPage) | Returns a paginator with specified items per page |
| links() | Renders HTML pagination links in Blade views |
| currentPage() | Gets the current page number |
| total() | Gets total number of records |
| lastPage() | Gets total number of pages |
Key Takeaways
Use
paginate() on Eloquent queries to get paged results easily.Always call
links() in your Blade view to show navigation links.Pass a positive integer to
paginate() to set items per page.Avoid mixing
paginate() with skip() or take().The paginator provides useful info like current page and total pages.