How to Create Pagination in Laravel 5?

 

Pagination play an important role in the field of web applications.As your website gets older, the database grows.So it is very difficult to show all data at once because it slows down your page loading, i.e. it takes more time to load large amount of data in the web page.To prevent this problem we split the data to display them into multiple pages where you can show limited number of data.In this article I am going to show you how to use pagination in laravel 5 using MySQL Database.

Database:
Below is the country table structure.

CREATE TABLE country (
     country_id INT NOT NULL AUTO_INCREMENT,
     country_name varchar(30) NOT NULL,
     PRIMARY KEY (country_id)
);

Routes:
Add below code in your app/Http/routes.php file.

Route::get('country', 'CountryController@index');

There are different ways to paginate your data in laravel 5 which are discussed below:-

Paginate your result using laravel 5 Eloquent Query or Query Builder

Below 2 methods are used by the eloquent query or query builder. You can use any method to paginate your result.

a)paginate method (It displays range of links like google pagination).
b)simplePaginate method (It displays only Next and Previous Link).

Controller:
Create a controller under App/Http/Controllers/CountryController.php and add following code.

<?php
namespace App\Http\Controllers;
use DB;
use App\Http\Controllers\Controller;

class CountryController extends Controller
{
    /**
     * Display all country list
     */
    public function index()
    {
        $countries = DB::table('country')->paginate(15); //Pass how many record you want to display per page

        return view('country.index', ['countries' => $countries]);
    }
}
?>

By default paginate method displays 15 records per page and it retrieves all columns from the table and generate page number with ?page query string. If you want to display 20 records per page or retrieve few columns from the table or change the page query string variable then below is the code you need to change.

<?php
$countries = DB::table('country')->paginate(20,array('country_name','country_capital'),'page_number');
?>

Blade Template File:
Create a template file under resources/views/country/index.blade.php
Now add the below code in your template file which will list all data and generate a pagination link.

<html>
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">  
    <table border="0" cellpadding="0" cellspacing="0" class="table table-striped">
    @if(count($countries)>0) {{-- If there is data then display it --}}
    <thead>
      <tr>
        <th>Country Id</th>
        <th>Country Name</th>
      </tr>
    </thead>
    <tbody>
    @foreach ($countries as $country_data)
    <tr>
      <td>{{ $country_data->country_id}}</td>
      <td>{{ $country_data->country_name}}</td>
    </tr>
    @endforeach
    </tbody>
    <tr>
      <td colspan="2">
      	<div class="pagination">{!! str_replace('/?', '?', $countries->render()) !!}</div>      
      </td>
    </tr>
    @else
    <tr>
      <td>No record found</td>
    </tr>
    @endif
    </table>
  </div>
</body>
</html>

In the above template file I have used {!! str_replace(‘/?’, ‘?’, $countries->render()) !!} because when the pagination generate the link, for next or previous page it adds extra slash(/) along with your current page URL like “/?page=2″ instead of “?page=2″. So when you click on that link it generates an error. To work it properly we replace the “/?” to “?”.

When you call the render() method in your blade template, by default it generates ?page query string variable.If you want to change this then call this method i.e $countries->setPath(‘index’); just above render() method which will now change the query string variable to ?index

How to Manually Create Pagination in Laravel 5?

You can manually create pagination in laravel 5 using Paginator or LengthAwarePaginator instance as per your requirements. When you use LengthAwarePaginator instance you need to pass the total number of records whereas in Paginator instance it is not required.

If you want to use Paginator instance the replace the code in your controller with below code.

<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use DB;
use Illuminate\Pagination\Paginator;

class CountryController extends Controller
{
    /**
     * Display all country list
     */
    public function index()
    {
       // $countries = DB::table('country')->paginate(5); //Pass how many record you want to display per page
		$page = Paginator::resolveCurrentPage();
		$perPage=1;		
		$countries = new Paginator(DB::table('country')->skip(($page - 1) * $perPage)->take($perPage + 1)->get(), $perPage, $page);
        return view('country.index', ['countries' => $countries]);
    }
}
?>

If you want to paginate your result using LengthAwarePaginator instance, then replace your controller with this code.

<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use DB;
use Illuminate\Pagination\LengthAwarePaginator;

class CountryController extends Controller{
	public function index(){
		$page = LengthAwarePaginator::resolveCurrentPage();
		$total=DB::table('country')->count('country_id'); //Count the total record
		$perPage=1;
		
		//Set the limit and offset for a given page.
		$results = DB::table('country')->forPage($page, $perPage)->get(['country_name','country_id']);
		$countries=new LengthAwarePaginator($results, $total, $perPage, $page, [
			'path' => LengthAwarePaginator::resolveCurrentPath(),
		]);
		return view('country.index', ['countries' => $countries]);
	}
}
?>

Output:
Below is the output of pagination result.
How to Create Pagination in Laravel 5

Pagination has more Helper methods which are discussed below:

Method Name Description
$results->count() It returns number of records for current page
$results->currentPage() Returns the current page number
$results->hasMorePages() It checks whether there are more pages
$results->nextPageUrl() It returns the full url of next page
$results->perPage() How many records will show per page
$results->previousPageUrl() It returns the full url of previous page
$results->url($page) Returns the url for given page number
$results->lastPage() Returns the last page number
(In simplePaginate this method does not exist)
$results->total() Returns the total number of items being paginated
(In simplePaginate this method does not exist)

Keep in touch for more tutorials.

COMMENTS ( 5 )

I got this website from my friend who told me
about this site and now this time I am browsing this web
page and reading very informative content here.

Reply

Leave a comment

SUBSCRIBE TO NEWSLETTER

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Categories