Laravel Pagination

Impletemention of pagination can be very painful in other frameworks.Laravel makes it a easy.

How pagination works

Pagination is technique to split a large collection of results over a number of pages.Pagination select a specific chunk of results from the database to display to the user.

<< First 2 3 4 Last >>

Laravel Pagination Example

Paginate is simplest method for creating pagination in laravel.We will use following step to perform Pagination operation in Laravel. Step 1

First We create table.

  `firstName` varchar(50) DEFAULT NULL,
  `class` char(20) DEFAULT NULL,
   PRIMARY KEY (`id`)
INSERT INTO `student`(`id`,`firstName`,`class`) VALUES (NULL,'Manish','Grade-12');
INSERT INTO `student`(`id`,`firstName`,`class`) VALUES (NULL,'Pawan','Grade-11');
INSERT INTO `student`(`id`,`firstName`,`class`) VALUES (NULL,'Kripal','Grade-10');
INSERT INTO `student`(`id`,`firstName`, `class`) VALUES (NULL, 'Priya', 'Grade-12');
INSERT INTO `student`(`id`,`firstName`, `class`) VALUES (NULL, 'Payal', 'Grade-11')  
INSERT INTO `student`(`id`,`firstName`,`class`) VALUES (NULL,'Pradeep','Grade-10'); 
INSERT INTO `student`(`id`,`firstName`,`class`) VALUES (NULL,'Punit','Grade-12');
Step 2

Now we create route for pagination inside app/routes.php.

Route::any('laravelpagination/',array('as' => 'laravelpagination',
                               'uses' => '[email protected]'));
Step 3

Create Controller file inside app/controllers/LaravelPagination.php.

class LaravelPagination extends Controller {

  protected function index()

        $data= DB::table('student')->paginate($per_page);
        return View::make('pagination',compact('data'));

Step 4

Create view file inside app/views/pagination.php

<title>Laravel pagination example :</title>
<link rel="stylesheet" href="">
<div class="container-fluid">
<tr><td>First Name</td>
<?php foreach ($data as $rows): ?>
<tr><td><?php echo $rows->firstName; ?></td>
<td><?php echo $rows->class; ?></td>
<?php endforeach; ?>
<?php echo $data->links() ?>
Total Record: <?php echo  $data->getTotal(); ?>
Step 5

Now we have to visit the following Url in our web browser.

http://mylaravel/laravelpagination // here mylaravel is my hostname

Other Methods

Laravel pagination class also provide some other useful methods.they are given below.

  • getCurrentPage
  • getLastPage
  • getPerPage
  • getTotal
  • getFrom
  • getTo
  • count