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
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.
Edit app\Http\Controllers\ArticleController.php
{
$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.
{!! $notes->links() !!}
</div>
- 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.
Edit app\Http\Controllers\ArticleController.php
{
$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.
{!! $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()
No comments:
Post a Comment