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.

CREATE TABLE student(
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `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.

<?php
class LaravelPagination extends Controller {

  protected function index()
  {

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

}?>
Step 4

Create view file inside app/views/pagination.php

<html>
<head>
<title>Laravel pagination example : Tutsway.com</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
<body>
<div class="container-fluid">
<table>
<tr><td>First Name</td>
<td>Class</td>
</tr>
<?php foreach ($data as $rows): ?>
<tr><td><?php echo $rows->firstName; ?></td>
<td><?php echo $rows->class; ?></td>
</tr>
</table>
<?php endforeach; ?>
<?php echo $data->links() ?>
Total Record: <?php echo  $data->getTotal(); ?>
</div>
</body>
</html>
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