Easy Pagination in Laravel 5.5 - Kollox Tutorial

Creating a working pagination in procedural PHP can be challenging, in Laravel 5.5 they have made it super easy!

What will you need in this tutorial?

1 - Create a database table called "companies" and add the below fields:


Here is the code for it:

CREATE TABLE `companies` (
`company_name` VARCHAR(100) NOT NULL COLLATE 'utf8mb4_unicode_ci',
`company_address` TEXT NOT NULL COLLATE 'utf8mb4_unicode_ci',
`company_phone1` VARCHAR(8) NULL DEFAULT NULL COLLATE 'utf8mb4_unicode_ci',

Now generate your model and controller

php artisan make:model Company

and controller

php artisan make:controller --resource CompanyController

Create a view folder called "company" in app/resources/view

In the "company" folder create a new view called "index.blade.php"

In the index.blade.php drop this code:

<div class="container">
    <div class="row">
        <div class="col-md-10 col-md-offset-1 animated fadeIn">
            <div class="panel panel-default">
                <div class="panel-heading" style="padding-bottom: 15px;">List of your companies
                <div class="btn-group pull-right">
                <a class="btn btn-success pull-right" href="{{ url('company/create') }}">Add new companie</a>
                <div class="panel-body">

                <div class="table-responsive">
                <table class="table">
                <th>Company name</th>
                <th>Company phone</th>
                 @foreach ($companies as $company)
                <td class="col-md-1">{{ $company->id }}</td>
                <td class="col-md-3">{{ $company->company_name }}</td>
                <td class="col-md-5">{{ $company->company_address }}</td>
                <td class="col-md-2">{{ $company->company_phone1 }}</td>
                <td class="col-md-1"><button class="btn btn-primary" type="submit">Edit</button></td>

                <div class="container">
                <nav aria-label="Page navigation">
                <ul class="pagination">
                {{ $companies->links() }}

Now add this code in your controller:

    public function myPagination()
        $companies = DB::table('companies')->paginate(5);
        return view('company.index',compact('companies'));

Make sure you add the classes at the top of your file:

use Illuminate\Support\Facades\DB;
use Illuminate\Pagination\Paginator;

Finally, in your web.php route file add this route:

Route::get('company', 'CompanyController@myPagination');  

Et voila!

What have we done?

We have first created a DB, then a model and a controller. In our controller we have added a new function which will fetch all the company rows from the database and return them to the view "company.index".

The laravel classes will do the rest of the job.

I have used Bootstrap 3 in this example. If you have a problem, leave a message below!

Leave us a comment