Pagination
- Eloquent pagination
- Manually create paginationCustom paging view
- Paginator instance method
Introduction
In other frameworks, pagination can be a pain. Laravel's paginator combines the query builder and Eloquent ORM to provide convenient and easy-to-use pagination of database result sets. HTML generated via the paginator is compatible with the Bootstrap CSS framework.
##Basic usage## Query builder paginationThere are several ways to paginate data. The simplest is to use the query builder or the Eloquent query's
paginatemethod.
paginatepaginate
The method automatically sets the appropriate offset offset and limit number based on the current page number browsed by the user. By default, thepage
query parameter value in the HTTP request is treated as the page number of the current page. Lavarel automatically detects this value and automatically inserts it into the link generated by the paginator.In the following example, the only parameter passed to the
method is the number of records you want to display on each page. Here we specify that we want to display
{note} Currently, Lavarel cannot perform efficiently using15
pieces of data per page:<?php namespace App\Http\Controllers; use Illuminate\Support\Facades\DB; use App\Http\Controllers\Controller; class UserController extends Controller{ /** * 显示应用程序中的所有用户。 * * @return Response */ public function index() { $users = DB::table('users')->paginate(15); return view('user.index', ['users' => $users]); } }
groupBy
Statement paging operation. If you need to paginate the result set using
groupBy
, it is recommended that you manually query the database and create pagination.Simple pagingIf you only need to simply display the "next page" and "previous page" links in your paginated view, you can Use the
simplePaginatemethod to perform more efficient queries. This is useful when you have a lot of data and don't need to display the page number of each page when rendering the view:
$users = DB::table('users')->simplePaginate(15);
Eloquent PaginationYou can also paginate Eloquent query results. In the example below, we will paginate the
Usermodel by
where15
items per page. As you can see, the syntax is basically the same as query builder pagination:
You can also set clauses such as$users = App\User::paginate(15);
in the query before calling
simplePaginatepaginate
Other constraints:
You can also use$users = User::where('votes', '>', 100)->paginate(15);
method in Eloquent paging:
$users = User::where('votes', '>', 100)->simplePaginate(15);
Create pagination manually
Sometimes you may want to create pagination manually and pass it an array set. This can be accomplished by creating an instance of
Illuminate\Pagination\Paginator
orIlluminate\Pagination\LengthAwarePaginator
, depending on your needs. The .Paginator
class does not need to know the total number of the result set; however, this class has no way of knowing the index of the last page.LengthAwarePaginator
accepts almost the same parameters asPaginator
; however, it counts the total number of the result set.In other words,
Paginator
is equivalent to the query builder or Eloquent'ssimplePaginate
method, andLengthAwarePaginator
is equivalent topaginate
method.{note} When manually creating a paging instance, you need to manually "cut" the result array passed to the paging instance. If you're not sure about this, please refer to PHP's array_slice function.
Display the result set
When you call the
paginate
method, you will getIlluminate\Pagination\LengthAwarePaginator
instance. Call thesimplePaginate
method and get theIlluminate\Pagination\Paginator
instance. These objects provide several methods for analyzing result sets. In addition to these helper methods, pager instances are combined into iterators that can be looped over like arrays. Therefore, when the results are obtained, you can use the Blade to display data and render paging links:<div class="container"> @foreach ($users as $user) {{ $user->name }} @endforeach </div> {{ $users->links() }}
links
method to render links to the remaining pages in the result set. Each link contains thepage
URL variable. Remember,links
generated HTML is compatible with the Bootstrap CSS framework.Custom paginator URI
withPath
method allows you to customize the URI when generating pagination links. For example, if you want to generate a paginated link likehttp://example.com/custom/url?page=N
, you only need to pass thecustom/url
parameter towithPath
Method:Route::get('users', function () { $users = App\User::paginate(15); $users->withPath('custom/url'); // });
Append parameters to paging links
You can use the
appends
method to add query parameters to paging links. For example, to addsort=votes
to each page link, just callappends
:{{ $users->appends(['sort' => 'votes'])->links() }}
If you want to add a "hash fragment" to the paginator URL ”, you can use the
fragment
method. For example, to add#foo
to links on every page, just call thefragment
method like this:{{ $users->fragment('foo')->links() }}
Adjusting the Paginator Link Window
You can control how many additional links are displayed on each side of the paginator's "window". By default, three links appear on each side of the main pagination link. This value can be changed using the
onEachSide
method:{{ $users->onEachSide(5)->links() }}
Convert the result to JSON
The Laravel paginator class implements the
Illuminate\Contracts\Support\Jsonable
interface contract and provides thetoJson
method, which can easily convert the paging results into JSON. It can also be converted to JSON by returning a paginator instance from a route or controller action:Route::get('users', function () { return App\User::paginate(); });
The JSON from the paginator will include things like
total
,current_page
,last_page
and other metadata information. The actual result object will be provided via thedata
key of the JSON array. The following is an example of creating JSON by returning a paginator instance from a route:{ "total": 50, "per_page": 15, "current_page": 1, "last_page": 4, "first_page_url": "http://laravel.app?page=1", "last_page_url": "http://laravel.app?page=4", "next_page_url": "http://laravel.app?page=2", "prev_page_url": null, "path": "http://laravel.app", "from": 1, "to": 15, "data":[ { // 结果集对象 }, { // 结果集对象 } ] }
Custom Pagination View
By default, rendering views to display paginated links is compatible with the Bootstrap CSS framework. If you're not using Bootstrap, feel free to customize your own view to render these links. When calling the
links
method of a paginator instance, pass it the view name as the first argument:{{ $paginator->links('view.name') }} // Passing data to the view... {{ $paginator->links('view.name', ['foo' => 'bar']) }}
The easiest way to customize a paginated view is to use a
vendor The :publish
command will output them to theresources/views/vendor
folder:php artisan vendor:publish --tag=laravel-pagination
This command will output them to the
resources/views/vendor/pagination
folder Place these views. Thebootstrap-4.blade.php
file built into this folder provides the default paging view. This file can be edited to modify the pagination HTML.If you want to define a different file as the default paging view, you need to use the
defaultView
anddefaultSimpleView
methods of the pager inAppServiceProvider
:use Illuminate\Pagination\Paginator;public function boot(){ Paginator::defaultView('view-name'); Paginator::defaultSimpleView('view-name'); }
Pager instance methods
Each pager instance provides the following methods to obtain additional paging information::
Method Description ##$results->count() Get the current page data quantity.$results->currentPage() Get the current page number.$results->firstItem() Get the result number of the first piece of data in the result set.$results->getOptions() Get pager options.$results->getUrlRange($start, $end) Create a paginated URL range.$results->hasMorePages() Whether there are multiple pages.$results->lastItem() Get the result number of the last piece of data in the result set.$results->lastPage() Get the page number of the last page (invalid insimplePaginate ) .
$results->nextPageUrl() Get the URL of the next page.$results->onFirstPage() Whether it is the first page or not.$results->perPage() The number of data items per page.$results->previousPageUrl() Get the URL of the previous page.$results->total() Total data (invalid insimplePaginate ).
$results->url($page)
Get the URL of the specified page.