Pagination


Query constructor pagination

  • Eloquent pagination
  • Manually create pagination
    • Display paginated results
    • Convert the results to JSON
    Custom 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 pagination

    There are several ways to paginate data. The simplest is to use the query builder or the Eloquent query's

    paginate

    method. paginate The method automatically sets the appropriate offset offset and limit number based on the current page number browsed by the user. By default, the page 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

    paginate

    method is the number of records you want to display on each page. Here we specify that we want to display 15 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]);   
          }
       }

    {note} Currently, Lavarel cannot perform efficiently using
    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 paging

    If you only need to simply display the "next page" and "previous page" links in your paginated view, you can Use the

    simplePaginate

    method 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 Pagination

    You can also paginate Eloquent query results. In the example below, we will paginate the

    User

    model by 15 items per page. As you can see, the syntax is basically the same as query builder pagination:

    $users = App\User::paginate(15);
    You can also set clauses such as

    where

    in the query before calling paginate Other constraints:

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

    simplePaginate

    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 or Illuminate\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 as Paginator; however, it counts the total number of the result set.

    In other words, Paginator is equivalent to the query builder or Eloquent's simplePaginate method, and LengthAwarePaginator is equivalent to paginate 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 the simplePaginate method and get the Illuminate\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 the page 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 like http://example.com/custom/url?page=N, you only need to pass the custom/url parameter to withPath 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 add sort=votes to each page link, just call appends:

    {{ $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 the fragment 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 the toJson 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 the data 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 the resources/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. The bootstrap-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 and defaultSimpleView methods of the pager in AppServiceProvider:

    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::

    Get the current page data quantity. Get the current page number. Get the result number of the first piece of data in the result set. Get pager options. Create a paginated URL range. Whether there are multiple pages. Get the result number of the last piece of data in the result set. Get the page number of the last page (invalid in Get the URL of the next page. Whether it is the first page or not. The number of data items per page. Get the URL of the previous page. Total data (invalid in
    MethodDescription
    ##$results->count()
    $results->currentPage()
    $results->firstItem()
    $results->getOptions()
    $results->getUrlRange($start, $end)
    $results->hasMorePages()
    $results->lastItem()
    $results->lastPage()simplePaginate) .
    $results->nextPageUrl()
    $results->onFirstPage()
    $results->perPage()
    $results->previousPageUrl()
    $results->total()simplePaginate).
    $results->url($page)Get the URL of the specified page.
    This article was first published on the LearnKu.com website.