paging


brief introduction

In other frameworks, pagination can be a very painful thing, and Laravel makes it simple and easy to start. Larravel's pager and Query Builder and Eloquent ORM It is integrated together and provides convenient, easy-to-use paging based on database result sets out of the box. HTML compatibility generated by pager Bootstrap CSS Frame.

Basic use

Paging based on query builder

There are many ways to realize the paging function. The simplest way is to use Query Builder or Eloquent Query Provided paginate method. This method automatically sets the appropriate offset and limit based on the current user's viewing page, which means the page number and the number of pages displayed. By default, the current page queries string parameters through HTTP requests page Value judgment of. Of course, this value is automatically detected by Larravel, and then automatically inserted into the link generated by the pager.

Let's first look at how to call paginate method. In this case, pass to paginate The only parameter of is the number of pages you want to display. Here we specify the number of pages to display fifteen Pieces:

 <? php namespace App\Http\Controllers; use Illuminate\Support\Facades\DB; use App\Http\Controllers\Controller; class UserController extends Controller { /** *Show all users in the application * * @return Response */ public function index() { $users = DB::table('users')->paginate(15); return view('user.index', ['users' => $users]); } }

Note: At present groupBy The paging operation of cannot be effectively executed by Larravel, if you need to use it in the paging results groupBy , it is recommended that you manually query the database and then create a pager.

Simple Paging

If you only need to simply display the "next page" and "previous page" links in the paging view, you can use the simplePaginate Method to execute a more efficient query. This feature is useful when rendering views that contain large data sets and do not need to display every page number:

 $users = DB::table('users')->simplePaginate(15);

Paging based on Eloquent result set

You can also Eloquent The query results are paginated. In this example, we User The model is displayed in pages fifteen Records. As you can see, this syntax is similar to paging based on query builder:

 $users = App\User::paginate(15);

Of course, you can call the paginate , such as where Clause:

 $users = User::where('votes', '>', 100)->paginate(15);

You can also use the simplePaginate method:

 $users = User::where('votes', '>', 100)->simplePaginate(15);

Manually create a pager

Sometimes you may want to manually create a paging instance by passing array data. You can create a paging instance by Illuminate\Pagination\Paginator or Illuminate\Pagination\LengthAwarePaginator Instance.

Paginator Class does not need to know the total number of data items in the result set; However, because of this, this class does not provide a method to obtain the index of the last page. LengthAwarePaginator Receive parameters and Paginator Almost the same, the only difference is the total number of result sets it requires to be passed in.

let me put it another way, Paginator corresponding simplePaginate Method, and LengthAwarePaginator corresponding paginate method.

Note: When manually creating a pager instance, you should manually "slice" the result set passed to the pager. If you are not sure what to do, check the PHP function array_slice

Show paging results

When called paginate Method, you will get Illuminate\Pagination\LengthAwarePaginator Instance, while calling the method simplePaginate Will get Illuminate\Pagination\Paginator example. These objects provide relevant methods to describe these result sets. In addition to these auxiliary functions, the pager instance itself is an iterator, which can be called circularly like an array. Therefore, after obtaining the results, you can use them as follows Blade Display these results and render the page links:

 <div class="container"> @foreach ($users as $user) {{ $user->name }} @endforeach </div> {{ $users->links() }}

links Method will render links to other pages in the result set. Each link already contains page Query string variable. Remember, render Method generated HTML compatible Bootstrap CSS framework

Custom Paging Links

withPath Method allows you to customize the URI used by the pager when generating paging links. For example, if you want the pager to generate a shape like http://example.com/custom/url?page=N Should be passed custom/url reach withPath method:

 Route::get('users', function () { $users = App\User::paginate(15); $users->withPath('custom/url'); // });

Add Parameter to Paging Link

You can use appends Method to add query parameters to the paging link query string. For example, to add &sort=votes To each paging link, it should be called as follows appends

 {{ $users->appends(['sort' => 'votes'])->links() }}

If you want to add a "hash fragment" to the paging link, you can use fragment method. For example, to add #foo To the end of each paging link, call fragment method:

 {{ $users->fragment('foo')->links() }}

Adjust Paging Link Window

You can control how many additional links are displayed in each paging URL "window" (pager) in addition to the current page links. By default, there are three. You can use onEachSide Method to modify the default value:

 {{ $users->onEachSide(5)->links() }}

Convert the result to JSON

Larravel pager result class implements Illuminate\Contracts\Support\JsonableInterface Contract and provide toJson Method, so it is very simple to convert paging results into JSON. You can also convert it to JSON by returning the pager instance from a route or controller action:

 Route::get('users', function () { return App\User::paginate(); });

JSON converted from pager contains meta information such as total current_page last_page The actual result object data can be accessed through the data Key. The following is an example of JSON created through the pager instance returned from the 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":[ { // Result Object }, { // Result Object } ] }

Custom Paging View

By default, the view used to render paging links is compatible with the Bootstrap CSS framework. If you do not use Bootstrap, you can customize the view to render these links. When calling the links Method, pass the view name as the first parameter:

 {{ $paginator->links('view.name') }} //Transfer Data to View {{ $paginator->links('view.name', ['foo' => 'bar']) }}

However, the easiest way to customize the paging view is to use the vendor:publish Command to export view file to resources/views/vendor catalog:

 php artisan vendor:publish --tag=laravel-pagination

This command will drop the view to resources/views/vendor/pagination Directory, the default.blade.php The file corresponds to the default view file. Edit the file to modify the paging HTML.

If you want to specify another file as the default paging view, you can select it in the AppServiceProvider Using the pager in defaultView and defaultSimpleView method:

 use Illuminate\Pagination\Paginator; public function boot() { Paginator::defaultView('pagination::view'); Paginator::defaultSimpleView('pagination::view'); }

Pager Instance Method

Each pager instance can provide more paging information through the following methods:

method describe
$results->count() Get the number of items on the current page
$results->currentPage() Get the page number of the current page
$results->firstItem() Get the number of the first item in the result set partition
$results->getOptions() Get Paging Options
$results->getUrlRange($start, $end) Create a range of paging URLs
$results->hasMorePages() Determine whether there are enough items for paging
$results->items() Get all result items of the current page
$results->lastItem() Get the number of the last item in the result set partition
$results->lastPage() Get the page number of the last page (use simplePaginate Is invalid)
$results->nextPageUrl() Get the URL of the next page
$results->onFirstPage() Judge whether it is on the first page
$results->perPage() Number of items displayed per page
$results->previousPageUrl() Get the URL of the previous page
$results->total() Determine the total number of all matching items in the memory (use simplePaginate Is invalid)
$results->url($page) Get the paging URL of the given page number
$results->getPageName() Get the query string variable used to store the page
$results->setPageName($name) Set the query string variable used to store the page

Recommended articles:


give the thumbs-up Cancel Like Collection Cancel Collection

<<Previous: Query Builder

>>Next: transfer