What Are The Basic Usage Of Pagination Using Laravel

admin_img Posted By Bajarangi soft , Posted On 23-09-2020

There are several ways to paginate items. The simplest is by using the paginate method on the query builder or an Eloquent query. The paginate method automatically takes care of setting the proper limit and offset based on the current page being viewed by the user. By default, the current page is detected by the value of the page query string argument on the HTTP request. This value is automatically detected by Laravel, and is also automatically inserted into links generated by the paginator

What Are The Basic Usage of Pagination in laravel with example

Basic Usage

1.Paginating Query Builder Results


the only argument passed to the paginate method is the number of items you would like displayed "per page". In this case, let's specify that we would like to display 15 items per page:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class UserController extends Controller
{
    public function index()
    {
        $users = DB::table('users')->paginate(15);

        return view('user.index', ['users' => $users]);
    }
}
 

2.Paginating Eloquent Results

You may also paginate Eloquent queries. In this example, we will paginate the User model with 15 items per page. As you can see, the syntax is nearly identical to paginating query builder results:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class UserController extends Controller
{
    /**
     * Show all of the users for the application.
     *
     * @return Response
     */
    public function index()
    {
        $users = App\User::paginate(15);
        return view('user.index', ['users' => $users]);
    }
}
 

You may call paginate after setting other constraints on the query, such as where clauses:

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


You may also use the simplePaginate method when paginating Eloquent models:

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

3.Manually Creating A Paginator
 

Sometimes you may wish to create a pagination instance manually, passing it an array of items. You may do so by creating either an Illuminate\Pagination\Paginator or   Illuminate\Pagination\LengthAwarePag inator instance, depending on your needs.The Paginator class does not need to know the total number of items in the result set; however, because of this, the class does not have methods for retrieving the index of the last page. The LengthAwarePaginator accepts almost the same arguments as the Paginator; however, it does require a count of the total number of items in the result set.

4.Displaying Pagination Results in Blade File

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

{{ $users->links() }}

The links method will render the links to the rest of the pages in the result set. Each of these links will already contain the proper page query string variable. Remember, the HTML generated by the links method is compatible with the Bootstrap CSS framework.



Customizing The Paginator URI if you want the paginator to generate links like http://example.com/custom/url?page=N, you should pass custom/url to the withPath method:

Route::get('users', function () {
$users = App\User::paginate(15);

$users->withPath('custom/url');

//
});


Appending To Pagination Links to append sort=votes to each pagination link, you should make the following call to appends:

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


If you wish to append all current query string values to the pagination links you may use the withQueryString method:

{{ $users->withQueryString()->links() }}


If you wish to append a "hash fragment" to the paginator's URLs, you may use the fragment method. For example, to append #foo to the end of each pagination link, make the following call to the fragment method:

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



Adjusting The Pagination Link Window: 
You may control how many additional links are displayed on each side of the paginator's URL "window". By default, three links are displayed on each side of the primary paginator links. However, you may control this number using the onEachSide method:

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



5.Converting Results To JSON 
The Laravel paginator result classes implement the Illuminate \Contracts\Support \Jsonable Interface contract and expose the toJson method, so it's very easy to convert your pagination results to JSON. 

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


 
JSON created 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":[
        {
            // Result Object
        },
        {
            // Result Object
        }
   ]
}
 

 

6.Visit our site Customizing The Pagination View to see demo of pagination


7.Paginator Instance Methods

Each paginator instance provides additional pagination information via the following methods:

Method Description
$paginator->count() Get the number of items for the current page.
$paginator->currentPage() Get the current page number.
$paginator->firstItem() Get the result number of the first item in the results.
$paginator->getOptions() Get the paginator options.
$paginator->getUrlRange($start, $end) Create a range of pagination URLs.
$paginator->hasPages() Determine if there are enough items to split into multiple pages.
$paginator->hasMorePages() Determine if there is more items in the data store.
$paginator->items() Get the items for the current page.
$paginator->lastItem() Get the result number of the last item in the results.
$paginator->lastPage() Get the page number of the last available page. (Not available when using simplePaginate).
$paginator->nextPageUrl() Get the URL for the next page.
$paginator->onFirstPage() Determine if the paginator is on the first page.
$paginator->perPage() The number of items to be shown per page.
$paginator->previousPageUrl() Get the URL for the previous page.
$paginator->total() Determine the total number of matching items in the data store. (Not available when using simplePaginate).
$paginator->url($page) Get the URL for a given page number.
$paginator->getPageName() Get the query string variable used to store the page.
$paginator->setPageName($name) Set the query string variable used to store the page.

 

Related Post