Paginating records in Laravel

2024-04-27 10:44:50 Jay Dixit Laravel

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 record 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 the 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 the 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 a sample Example to implement pagination in Laravel 5.6 using DB facade and Eloquent way both.

Pagination using DB facade.

<?php

namespace App\Http\Controllers;

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

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 the 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 App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Models\Post;
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 the 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.

This post is submitted by one of our members. You may submit a new post here.

Related Tricks