When working with thousand or millions of record or working with bunch of data and need to show them then we need to divide into more pages to show all data in parts. to prevent millions of records show in a single page. records showing in parts is a good functionality to prevent query fails and long time process.
For this we need to use pagination (refers to links that allows you to navigate from page to page). so i am writing this article how to create pagination in laravel. We can easily create pagination in laravel with it’s own library also laravel provide twitter bootstrap pagination links for showing pagination counting.
laravel has paging configuration option in the “app/config/view.php” file. Laravel includes two views for pagination option to create pagination links :-
1. pagination::slider (shows “range” of links based on the current page)
2. pagination::simple (shows “previous” and “next” buttons)
Below we will see an example of how to create pagination in laravel :-
Controller :- create a controller under app/controllers/AccountController.php and add below code.
class AccountController extends BaseController {
public function paging() {
$users = User::paginate(15);
return View::make('paging', compact('users'));
}
}
View :- create a controller under app/views/paging.blade.php and add below code.
@extends('layout.default')
@section('content')
<div class="container">
<table width="60%" cellspacing="0" cellpadding="4" border="0" class="data">
@foreach($users as $user)
<tr>
<td> {{ $user->u_firstname }} </td>
<td> {{ $user->u_lastname }} </td>
<td> {{ $user->u_email }} </td>
</tr>
@endforeach
</table>
<div class="pagination"> {{ $users->links() }} </div>
</div>
@stop
Routes:- add below code in app/routes.php
Route::get('account/paging', 'AccountController@paging');
Simple Pagination :- if you want to show only “next” and “prev” link
$users = User::where('u_id', '>', 20)->simplePaginate(15);
create custom pagination in laravel :-
you can also create custom pagination using Paginator class Make() method. send your custom data to pagination
$paging = Paginator::make($items, $totalItems, $perPage);
//example
//$data = $this->user->mymethod();
//$users = Paginator::make($data->items, $data->totalItems, 50)