This package adds the paginate
route method to support pagination via custom routes instead of query strings. This also allows for easily translatable pagination routes ex. /news/page/2
, /nieuws/pagina/2
.
Via Composer
$ composer require spatie/laravel-paginateroute
First register the service provider and facade in your application.
// config/app.php
'providers' => [
...
'Spatie\PaginateRoute\PaginateRouteServiceProvider',
];
'aliases' => [
...
'PaginateRoute' => 'Spatie\PaginateRoute\PaginateRouteFacade',
];
Then register the macros in App\Providers\RouteServiceProvider::boot()
.
// app/Providers/RouteServiceProvider.php
use PaginateRoute;
// ...
public function boot(Router $router)
{
PaginateRoute::registerMacros();
parent::boot($router);
}
The paginate
route macro will register two routes for you.
// app/Http/routes.php
// Generates /users & /users/page/{page}
Route::paginate('users', 'UsersController@index');
In your route's action you can just use Laravel's regular pagination methods.
// app/Http/Controllers/UsersController.php
public function index()
{
return view('users.index', ['users' => \App\User::simplePaginate(5)]);
}
If you want to customize or add translations for the "page" url segment, you can publish the language files.
$ php artisan vendor:publish --provider="Spatie\PaginateRoute\PaginateRouteServiceProvider"
Since Laravel's paginator url's will still use a query string, PaginateRoute has it's own url generator and page helper functions.
{{-- $users is an instance of \Illuminate\Contracts\Pagination\Paginator --}}
@if(PaginateRoute::hasPreviousPage())
<a href="{{ PaginateRoute::previousPageUrl() }}">Previous</a>
@endif
@if(PaginateRoute::hasNextPage($users))
<a href="{{ PaginateRoute::nextPageUrl($users) }}">Next</a>
@endif
The nextPage
functions require the paginator instance as a parameter, so they can determine whether there are any more records.
/**
* @param \Illuminate\Contracts\Pagination\Paginator $paginator
* @return int|null
*/
public function nextPage(Paginator $paginator)
/**
* @param \Illuminate\Contracts\Pagination\Paginator $paginator
* @return bool
*/
public function hasNextPage(Paginator $paginator)
/**
* @param \Illuminate\Contracts\Pagination\Paginator $paginator
* @return string|null
*/
public function nextPageUrl(Paginator $paginator)
/**
* @return int|null
*/
public function previousPage()
/**
* @return bool
*/
public function hasPreviousPage()
/**
* @param bool $full
* @return string|null
*/
public function previousPageUrl($full = false)
If $full
is true, the first page will be a fully qualified url. Ex. /users/page/1
instead if just /users
(this is the default).
Please see CHANGELOG for more information what has changed recently.
Please see CONTRIBUTING for details.
If you discover any security related issues, please email freek@spatie.be instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.