How to paginate with Laravel — Very easy!

Hello everyone!
Pagination is a rather important feature which is used by virtually every single website, apps etc. This is because most websites deal with loads of data and loading them at once to the user can be so much pain to the end user.
It is very important to load small chunks of data at a time while giving the user ability to navigate to the next or previous available data.
Implementing pagination can be one hell of a daunting task on modern apps[hello android 😐!] or website. However, in laravel
this is very easy to do.
This tutorial assumes you already have a foundation/understanding of Laravel framework.
Check out my previous post if you are complete beginner.
LETS GOOO — -
Lets assume we were building a website that displays a list of blog posts.
There are 2 methods that you can use to implement pagination in your laravel app -
- paginate() — The
paginate
method counts the total number of records matched by the query before retrieving the records from the database. This is done so that thepaginator
knows how many pages of records there are in total.

2. simplePaginate() — If you only need to display a simple Next
and Previous
links in your application’s UI, you may use the simplePaginate
method to perform a single, efficient query.

Just pass paginate()
or simplePaginate()
method to the view you want to display the posts in your controller. The method carries one argument — number of records you want to display per post. For this example I used 10 so — paginate(10)
or simplePaginate(10)
depending on which you are using
PostController
postView.blade.php
In your view
, you only need to call $posts->links()
after your loop statement or anywhere you want the pagination to appear and you are done
Pagination with just few lines of code all set up for you.
Customizing Pagination
If you aren’t feeling the looks of the default pagination given by laravel
— You can customize it to your taste.
By default, the views rendered to display the pagination links are compatible with the Tailwind CSS
framework.
I used Bootstrap CSS framework here, If you want to use Bootstrap—
- Go to
App\Providers\AppServiceProvider
class - Add this to the
boot
function —
If you want to use your own custom styling for the pagination, you can do these
- Run
php artisan vendor:publish --tag=laravel-pagination
— This will export all the pagination views to yourresources/views/vendor
directory - The
tailwind.blade.php
file within this directory corresponds to the default pagination view. You may edit this file to modify the pagination HTML. - If you would like to designate a different file as the default pagination view, you may invoke the paginator’s
defaultView
anddefaultSimpleView
methods within theboot
method of yourApp\Providers\AppServiceProvider
class
Thanks for reading. Happy New Year!