How to make custom laravel pagination and display data ?

Builtin laravel pagination provides lot of features like page links, total items, no of pages, last page and many more. Laravel provides pagination with query builder and eloquent orm. We can use paginate function at the end of the query and then we can get paginated data.

However, sometime this might not be enough. For example, we have a large array of items and we want to disply paginated items then builtin laravel pagination might not be enough to solve our problem. Such problem normally happens when we have third party data or processed data.

We will use array of all countries and we will display paginated list of these countries.

At first lets create a controller.

php artisan make:controller CountryController

Now, we will define an array as controller class attribute and then we will add list of countries in it.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class CountryController extends Controller
{
    /**
     * @var array
     */
    private $countries;

    /**
     * CountryController constructor.
     */
    public function __construct()
    {
        $this->countries = array(
            "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla",
            "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria",
            "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize",
            "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegowina", "Botswana", "Bouvet Island",
            "Brazil", "British Indian Ocean Territory", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi",
            "Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands", "Central African Republic", "Chad", "Chile",
            "China", "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", "Congo, the Democratic Republic of the",
            "Cook Islands", "Costa Rica", "Cote d'Ivoire", "Croatia (Hrvatska)", "Cuba", "Cyprus", "Czech Republic", "Denmark",
            "Djibouti", "Dominica", "Dominican Republic", "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea",
            "Eritrea", "Estonia", "Ethiopia", "Falkland Islands (Malvinas)", "Faroe Islands", "Fiji", "Finland", "France", "France Metropolitan",
            "French Guiana", "French Polynesia", "French Southern Territories", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar",
            "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau", "Guyana", "Haiti",
            "Heard and Mc Donald Islands", "Holy See (Vatican City State)", "Honduras", "Hong Kong", "Hungary", "Iceland", "India",
            "Indonesia", "Iran (Islamic Republic of)", "Iraq", "Ireland", "Israel", "Italy", "Jamaica", "Japan", "Jordan", "Kazakhstan",
            "Kenya", "Kiribati", "Korea, Democratic People's Republic of", "Korea, Republic of", "Kuwait", "Kyrgyzstan",
            "Lao, People's Democratic Republic", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libyan Arab Jamahiriya", "Liechtenstein",
            "Lithuania", "Luxembourg", "Macau", "Macedonia, The Former Yugoslav Republic of", "Madagascar", "Malawi", "Malaysia", "Maldives",
            "Mali", "Malta", "Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia, Federated States of",
            "Moldova, Republic of", "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands",
            "Netherlands Antilles", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "Northern Mariana Islands",
            "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn", "Poland", "Portugal",
            "Puerto Rico", "Qatar", "Reunion", "Romania", "Russian Federation", "Rwanda", "Saint Kitts and Nevis", "Saint Lucia",
            "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal", "Seychelles",
            "Sierra Leone", "Singapore", "Slovakia (Slovak Republic)", "Slovenia", "Solomon Islands", "Somalia", "South Africa",
            "South Georgia and the South Sandwich Islands", "Spain", "Sri Lanka", "St. Helena", "St. Pierre and Miquelon", "Sudan",
            "Suriname", "Svalbard and Jan Mayen Islands", "Swaziland", "Sweden", "Switzerland", "Syrian Arab Republic", "Taiwan, Province of China",
            "Tajikistan", "Tanzania, United Republic of", "Thailand", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia",
            "Turkey", "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom",
            "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela", "Vietnam",
            "Virgin Islands (British)", "Virgin Islands (U.S.)", "Wallis and Futuna Islands", "Western Sahara", "Yemen", "Yugoslavia", "Zambia", "Zimbabwe");

    }
    
}

Now, lets define route and controller function where we will write all logic to paginate this data.

Route::get('countries', 'CountryController@index')->name('countries.list');

After this we will create an index function in country controller.

public function index(Request $request)
{
        // Here we will write logic
}

We will use laravel Illuminate\Pagination\LengthAwarePaginator to paginate the above data. For this, we need total no of items, items per page, and items for current page.

// no of items per page
$perPage = 10;

// total no of items
$totalItems = count($this->countries);

// items for current page
$currentPage = $request->input('page', 1);
        
// location after that we will take items for current page
$offset = ($perPage-1) * $currentPage;

// items for current page
$itemsForThisPage = array_slice($this->countries, $offset, $perPage);

Now, we will create paginator using all these of these data and then we will set custom url for links of pages.

// paginated data
$countries = new LengthAwarePaginator($itemsForThisPage, $totalItems, $perPage, $currentPage);

// set url for page links
$countries->withPath('/countries');

Also Read: How to send firebase notification in android devices in laravel ?

Now pagination is created. Finally our functionality looks like:

   /**
     * Show paginated list of countries
     * 
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        // no of items per page
        $perPage = 10;

        // total no of items
        $totalItems = count($this->countries);

        // items for current page
        $currentPage = $request->input('page', 1);

        // location after that we will take items for current page
        $offset = $perPage * ($currentPage-1);

        // items for current page
        $itemsForThisPage = array_slice($this->countries, $offset, $perPage);

        // paginated data
        $countries = new LengthAwarePaginator($itemsForThisPage, $totalItems, $perPage, $currentPage);

        // set url for page links
        $countries->withPath('/countries');

        return view('countries', compact($countries));
    }

We will display pagination in blade view. Lets create countries.blade.php inside resources/views directory and add following code inside.

@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="row">
            <div class="col-md-8">
                <div class="card">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>S.N.</th>
                                <th>Name</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($countries as $country)
                                <tr>
                                    <td>{{$loop->iteration}}</td>
                                    <td>{{$country}}</td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                    {{$countries->links()}}
                </div>
                </div>
            </div>
        </div>
    </div>
@endsection

Now, when you hit url '/countries', You will see something like this:

In this way, we can easily make custom laravel pagination for custom data and then display in the tabular format. It's pretty simple.


share :

Sagar Gautam

A Computer Engineer from Nepal.


Leave your Feedback