Pagination in Laravel
According to Wikipedia Pagination is a process of separating or dividing a document or digital contents into discrete pages.In CORE PHP and other frameworks, paginating records is a painful task. Laravel Pagination provides convenient and easy-to-use database records pagination with the help of Laravel’s paginator which is integrated by default with query builder and Eloquent ORM.
Here in this article, we are going to see how easy to implement pagination in Laravel.
While using Laravel you will find several methods to paginate records. Paginate method is simplest and easiest way to implement Laravel Paginations.It will automatically configure the pagination’s limit and offset based on the current page user is browsing.
Here is sample Example to implement pagination in Laravel 5.6 using DB facade and Eloquent way both.
Pagination using DB facade.
<?php namespace AppHttpControllers; use IlluminateSupportFacadesDB; use AppHttpControllersController; class PostController extends Controller { /** * Show all of the users for the application. * * @return Response */ public function index() { $posts= DB::table('posts')->paginate(10); return view('post.index', ['posts' => $posts]); } }
Pagination Code Explanation
In above example, we have created a sample Post controller and used DB facade to paginate our posts table data to 10 records.
Pagination using Eloquent Paginate method.
<?php namespace AppHttpControllers; use IlluminateSupportFacadesDB; use AppHttpControllersController; use AppModelsPost; class PostController extends Controller { /** * Show all of the users for the application. * * @return Response */ public function index() { $posts= Post::paginate(10); return view('post.index', ['posts' => $posts]); } }
Code Explanation
In above example, we have created a sample Post controller and used Eloquent to paginate our posts table data to 10 records.
Displaying Results and paginations links in our View
<div class="container"> @foreach ($posts as $post) {{ $post->title}} @endforeach </div> {{ $posts->links() }}
Hope you understood how to implement pagination in Laravel.
Laravel Pagination |
||
---|---|---|
Pagination in Laravel Framework |
The post Laravel Pagination appeared first on Laravel Interview Questions.
Source: laravelinterviewquestions.com