Laravel Simple Pagination Example Tutorial (Laravel 9)

In today’s landscape, where over 717,606 web applications are already leveraging the power of Laravel, this PHP framework has firmly established itself as a go-to choice for ensuring a seamless and efficient user experience. There are compelling reasons to consider Laravel integration into your web development projects.

Here is a scenario explaining it a bit more; your application needs to display a vast dataset, potentially containing hundreds or thousands of records. Would you want to present all of this data on a single page? Most likely not.

The idea of showcasing such a substantial amount of information on a single page is not just impractical but also counterproductive, as it can overwhelm users and adversely affect the performance of your web application.

Fortunately, there’s a solution available on hand: pagination. Before we delve into the nitty-gritty of code implementation, it’s crucial to understand the concept of pagination and recognize why it serves as a fundamental element in creating user-friendly web interfaces. So, let’s dive into it.

What is Laravel Pagination?

First of all, let’s understand the term ‘pagination’ – Basically, it is a practice that includes the process of dividing a large set of data into smaller, manageable chunks or pages.

Instead of displaying all the data on a single page, this pagination feature allows users to navigate through the data with a specific amount of information, improving the overall user experience.

Compared to others, the process of adding pagination in the Laravel 9 framework is way easier. Even for the configuration, there is only a single approach you need to conduct in the app/config/view.php file.

By default, Laravel 9 includes two pagination view options from which you can select the one you want to use – for creating the pagination links. Using the pagination::slider view will display a ‘range’ of context based on the current page.

While on another hand, pagination::simple can help you if you want to give your context a simple breakdown. This pagination::simple will add the ‘previous‘ and ‘next‘ buttons to your huge dataset. Both of these views are completely compatible with Twitter Bootstrap out of the box

Prerequisites for Laravel 9 Simple Pagination Example Using Bootstrap

Before we begin, ensure you have the following prerequisites in place:

1. Laravel 9: Make sure you have a Laravel 9 project set up. You can create one using the Laravel installer or Composer.

2. Database Setup: You should have a database configured for your Laravel project. If not, set up a database and configure it in your `.env` file.

3. Faker Library: If you haven’t already installed the Faker Library, you can do so using Composer:

composer require fzaninotto/faker

Steps to Laravel 9 Simple Pagination Example Using Bootstrap

By the release in February 2022, there are many features and advancements in Laravel 9 – pagination is one of them. Also, the Laravel framework offers a breeze to create the same. Here’s a step-by-step guide on Laravel 9 pagination example using Bootstrap:

Step 1: Create Migrations for Categories and Blogs

Let’s start by creating migrations for the `categories` and `blogs` tables. Run the following Artisan commands:

php artisan make:model Category -m
php artisan make:model Blog -m

This will generate model files in the `app/Models` directory and migration files in the `database/migrations` directory.

Step 1.1: Category Migration

Open the generated migration file for the `categories` table (e.g., `create_categories_table.php`) and define the schema:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCategoriesTable extends Migration
{
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('categories');
    }
}

Run the migration to create the `categories` table:

php artisan migrate

Step 1.2: Blog Migration

Open the generated migration file for the `blogs` table (e.g., `create_blogs_table.php`) and define the schema for blogs:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateBlogsTable extends Migration
{
    public function up()
    {
        Schema::create('blogs', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->unsignedBigInteger('category_id'); // Add foreign key for category
            $table->text('description');
            $table->string('tags');
            $table->integer('read_minutes');
 	$table->integer('status')->default(0);
            $table->timestamps();
            $table->foreign('category_id')->references('id')->on('categories');
        });
    }
    public function down()
    {
        Schema::dropIfExists('blogs');
    }
}

Step 2: Run Migrations and Create Seeders

Now, execute the migrations to create the `categories` and `blogs` tables:

php artisan migrate

2.1: Create Seeders

Generate seeders for both the `categories` and `blogs` tables:

php artisan make:seeder CategoriesTableSeeder
php artisan make:seeder BlogsTableSeeder

2.2: Update Category Seeder

Open the generated seeder file for the `categories` table (e.g., `CategoriesTableSeeder.php`) and define the logic for populating categories:

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;
class CategoriesTableSeeder extends Seeder
{
    public function run()
    {
        $faker = Faker::create();
        foreach (range(1, 5) as $index) {
            DB::table('categories')->insert([
                'name' => $faker->word,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }
    }
}

2.3: Update Blog Seeder

Open the generated seeder file for the `blogs` table (e.g., `BlogsTableSeeder.php`) and define the logic for populating blogs:

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;
class BlogsTableSeeder extends Seeder
{
    public function run()
    {
        $faker = Faker::create();
        foreach ( range (1, 50) as $index ) {
            $categoryId = rand(1, 5); // Assuming you have 5 categories
            DB::table('blogs')->insert([
                'title' => $faker->sentence,
                'category_id' => $categoryId,
                'description' => $faker->paragraph,
                'tags' => $faker->words(3, true),
                'read_minutes' => rand(1, 30),
       	 'status' => rand(0, 1),
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }
    }
}

In this example, we’re populating the `blogs` table with 50 fake blog entries with titles, categories, descriptions, tags, and read times.

Step 3: Implement Pagination

Now that we have our database ready, let’s implement pagination to display the blogs in a paginated list.

3.1: Define a Route:

Open your `routes/web.php` file and add a new route for the page where you want to display the paginated blogs:

use Illuminate\Support\Facades\Route;
use App\Http\Controller\BlogController;
Route::get('/blogs', 'BlogController@index');

3.2: Create a Controller:

Generate a controller that will handle the logic for fetching and displaying the paginated blogs:

 php artisan make:controller BlogController

In the `BlogController.php` file, define the `index` method to fetch and paginate the blogs:

   use App\Models\Blog;
   public function index()
   {
       $blogs = Blog::samplePaginate(10); // Paginate with 10 items per page
       return view('blogs.index', compact('blogs'));
   }

Here, we’re using the `paginate` method to retrieve blogs from the database and paginate them with 10 items per page. You can adjust the number as needed.

3:3 Create a Blade View:

Create a Blade view file to display the paginated data. In the `resources/views` directory, create a new directory called `blogs`, and inside it, create a file named `index.blade.php`. This is where we’ll render the paginated data:

 @extends('layouts.app')
   @section('content')
       <h1>Blog List</h1>
       <div class=”row”>
       	<div class=”col-12”>
 	 <table class="table table-hover">
                    <thead>
                        <tr>
                            <th scope="col"> SR. NO</th>
                            <th scope="col"> Blog Title</th>
                            <th scope="col"> Category</th>
 		 <th scope="col"> Tags</th>
 		 <th scope="col"> Read Minutes</th>
                            <th scope="col"> Status</th>  
                        </tr>
                    </thead>
                    <tbody>
                        @if(count($blogs) > 0)
      		 @php $i = 0; @endphp
                             @foreach ($blogs as $blog) 
                                <tr>
                                    <th scope="row">{{ ++$i }}</th>
                                    <td>{{ $blog->title }}</td>
                                    <td>{{ $blog->category->name }}</td>
 			 <td>{{ $blog->tags }}</td>
 			 <td>{{ $blog->read_minutes }} minutes</td>
 			 <td>{{ $blog->status ? “Active” : “Deactive” }}</td>
                                </tr>
                            @endforeach
                        @else
                            <tr>
                                <th colspan="3" class="text-center">No data found</th>
                           </tr>
                        @endif
                    </tbody>
                </table>
 	 {!! $blogs->links() !!}
  	</div>
       </div>   
   @endsection

In this view, we loop through the `$blogs` collection and display each blog’s title, category, description, tags, read minutes, and status. The `{!! $blogs->links() !!}` method generates the pagination links for us.

3.4 Access Your Paginated Blog List:

You can now access your paginated blog list by visiting the `/blogs` route in your Laravel application. You’ll see a list of blogs with pagination links at the bottom, allowing you to navigate through the pages.

Expected Output:

laravel simple pagination output

Haven’t got the same result? Hire dedicated Laravel developers today!

FAQs About Laravel 9 Pagination Example

What is the difference between paginate and simplePaginate in Laravel?
The difference is noticed in the display. The paginate() view displays the 'range' of links based on the current page's context. On the other hand, simplePaginate() sets a simple pagination example by adding only the Prev and Next buttons.
Is Laravel 9 pagination custom?
Laravel 9 enables developers to display pagination in multiple ways; as a standard example, you can consider it in numerical, previous/next buttons, and even custom pagination.
What is the difference between Lazyload and pagination?
Pagination is the process of dividing an extensive data set into smaller chunks or pages that can be accessed sequentially or randomly. Lazy loading is the technique of loading data only when it is required rather than loading all the data at once.

Conclusion

In this blog post, first, we discussed the importance of pagination. Then, after being quite familiar with the pagination term itself and default pagination layouts offered by Laravel v9 – we moved to a step-by-step guide for creating a simple example of Laravel Pagination.

We’ve also noticed that Laravel’s simplePaginate() method simplifies adding pagination to your Laravel project, which is a significant takeaway from this blog. It allows you to focus on building great web applications. Experiment with different pagination settings and styles to find the best fit for your project. 

Undoubtedly, by following this guide, you can enhance the user experience of your Laravel web application with pagination.

But still, not to forget, being part of programming – each framework has its own complexities, and so does Laravel. In such cases, it’s common to seek the help of Laravel professionals, and you can do the same while also obtaining a free quote!

author
Mayur Upadhyay is a tech professional with expertise in Shopify, WordPress, Drupal, Frameworks, jQuery, and more. With a proven track record in web development and eCommerce development.

Leave a comment