Monday, June 28, 2021

Pagination within Laravel

One of the most common operations in Laravel involves the index.blade.php file. It displays a list of all the contents that an object retrieves from the database. In situations where there are thousand of rows of data, the view would best display it across many pages.

In Laravel, Pagination by default is compatible with Tailwind CSS framework and Bootstrap 4. When the number of rows are huge, its essential that the database column where the "whereby" clause is used, is index. 

Lets see 2 methods to apply pagination in a Laravel project using Bootstrap 4. 

Edit file App\Providers\AppServiceProvider.php

public function boot(){
  Paginator::useBootstrap();
}

Lets consider ArticleController that retrieves Article objects from the database through the function index(). This will display all the articles through a View called index.blade.php. For simplicity, only a total of 3 items will be displayed per page. 


Method 1: Using Paginate

Users will be able to view pagination with page numbers.

Pagination display


Edit app\Http\Controllers\ArticleController.php

public function index()
{
   $itemsPerPage = 3;
   $notes = Note::latest()->paginate($itemsPerPage);
   return view('notes.index', compact('notes'));
}

Edit resources\views\articles\index.blade.php and below the displayed date listing add the pagination.

<div>
{!! $notes->links() !!}
</div>

Additional functions available to use with Paginator

  • Number of items in current page $notes->count()
  • Current page number $notes->currentPage() 
  • Last page available $notes->lastPage()


Method 2: Using Cursor

Users will be able to view pagination with only the previous, and next navigation.

Cursor pagination


Edit app\Http\Controllers\ArticleController.php

public function index()
{
   $itemsPerPage = 3;
   $notes = Note::latest()->cursorPaginate($itemsPerPage);
   return view('notes.index', compact('notes'));
}

Edit resources\views\articles\index.blade.php and below the displayed date listing add the pagination.

<div>
{!! $notes->links() !!}
</div>


Additional functions available to use with Cursor

  • Number of items in current page, $notes->count()
  • Determine if cursor is on the first page, $notes->onFirstPage() 
  • Returns value of 1 if there are more pages to be split, $notes->hasMorePages()

Customise Pagination

This can be done by generating the required pagination files for customisation.

php artisan vendor:publish

Then select laravel-pagination and press enter. Find the files in the folder vendor/pagination in the project's view folder. Edit default.blade.php for a custom pagination layout. Here is an example of a customised Paginate.




Blog Archive