In other frameworks pagination is headache. Laravel makes it breeze, it can generate pagination by adding few lines of code in Controller and View.
Basic Usage
There are many ways to paginate items, but the simplest one is using the paginate method on query builder or an Eloquent query. Laravel out of the box take care of setting limit and offset based on the current page being viewed by user. By default, the current page is detected by the value of ?page query string argument on the HTTP request. And for sure, this value is detected by Laravel automatically and insert into links generated by paginator.
Now let's say we want to call the paginate
method on query. In our example the passed argument to paginate is the number of items you would like to display "per page". In our case, let say we want to display 10 items per page.
<?php
namespace App\Http\Controllers;
use DB;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
/**
* Show all of the users for the application.
*
* @return Response
*/
public function index()
{
$users = DB::table('users')->paginate(10);
return view('user.index', ['users' => $users]);
}
}
Note: Currently, pagination operations that use a
groupBy
statement cannot be executed efficiently by Laravel. If you need to use agroupBy
with a paginated result set, it is recommended that you query the database and create a paginator manually.
Simple Pagination
Let say you just want to display Next and Previous links on your pagination view. Laravel provides you this option by using simplePaginate
method.
$users = DB::table('users')->simplePaginate(10);
Displaying Results In A View
Now lets display the pagination in view. Actually when you call the paginate
or simplePaginate
methods on Eloquent query, you receive a paginator instance. When paginate method is called, you receive an instance of Illuminate\Pagination\LengthAwarePaginator
, while when you call simplePaginate
method, you receive an instance of Illuminate\Pagination\Paginator
. These instances / objects comes with several methods that explaines the result set. Moreover, in addition to these helpers methods, the paginator instances are iterators and can be looped as an array.
Once you received the results, you can easily render the page links using blade
<div class="container">
@foreach ($users as $user)
{{ $user->name }}
@endforeach
</div>
{{ $users->links() }}
The links
method will automatically render the links to other pages in result set. Each of these links will contain the specific page number i.e ?page
query string variable. The HTML generated by the links method is perfectly compatible with the Bootstrap CSS framework.