Custom Bootstrap Pagination in Laravel

Use Bootstrap components to create a pagination for your custom collections

Last time I wrote about how Laravel Bootstrap Components can clean up your view files. Today I want to show how you can use this package to create a pagination with rendered Bootstrap buttons, for your custom collections.


  • Laravel 5.4+
  • Bootstrap 4
  • Bootstrap components installed according to the instructions:
  • Alias for Bootstrap components, add to config/app.php: ‘BootstrapComponents’ => Appstract\BootstrapComponents\BootstrapComponentsFacade::class

Creating the pagination

If you use a database model, you can easily use the pagination options to handle the pagination. If you don’t use a database model, the easiest method of creating a pagination is to use a collection, which I use in this example.

Determine the current page

First we need some ‘logic’ to determine which page we want to display. The most used method is to append a parameter to the URL which contains the page number: ?page=2. In your controller you can get this parameter with $request->get(‘page’, 1), default set to page 1.

Create the collection

Now we can create the collection of items we want to display. First do your thing with retrieving your data (from an array, API, file system or something else) and wrap it in the collect method: collect($myItems).

With the collection, we can now return the right chunk of data to the view with: $items->forPage($page, $perPage) where $items is your collection.

Render the buttons

The next thing to do is to create the navigation buttons. Normally this can be a though task. That’s why we included a handy method in The Bootstrap Components package which takes care of this. Simply return the following to your view:

‘pagination’ => BootstrapComponents::pagination($items, $page, $perPage)

Where $items is your full collection, this is used to count the items and calculate the needed buttons. There is also a 4th and 5th parameter, the 4th is a custom URL you want to prepend to the generated links. The 5th is an array of options for the component (class name and if you want to display arrows). Example:

$items, $page, $perPage, 'someotherpage',
'class' => 'justify-content-end',
'arrows' => true

Your controller method should now look something like this:

Last thing to do is to add {{ $pagination }} to the view where you want it to display.

That’s it! We now have some nice working pagination buttons!

← more stories in Appstract

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.