Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Laravel 11 Pagination with Relationship Tutorial

Last Updated on June 17, 2024 by

In Laravel 11 it has become very simple to fetch data from a table 2 or more tables with the help of Relationship Eloquent and display it using paginate() method.

Let’s start creating functionality that will help us show pagination with relation data in views in laravel:

Step 1 – Create Model and Migration

Run the following command to create model and migration for tables:

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

Edit database/migrations/_create_posts_table.php, and add the following code in it:

    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('slug');
            $table->text('body');
            $table->integer('category_id');
            $table->timestamps();
        });
    }

Edit database/migrations/_create_categories_table.php, and add the following code in it:

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

 Run the following migration command:

php artisan migrate

Step 2 – Define Relationship in Models

Edit app/Models/Category.php file, and define relationship between category and post table:

    public function posts(): HasMany
    {
        return $this->hasMany(Post::class);
    }

Edit app/Models/Post.php file, and define relationship between post and category table:

    public function category(): BelongsTo
    {
        return $this->belongsTo(Category::class);
    }

Step 3 – Add Dummy Data in Database

Run the following command to create a seeder file, with the help of this file we can add data to the categories and posts table:

php artisan make:seeder CreatePosts

Edit database/seeders/CreatePosts.php file, and add dummy records to it, with the help of this we will insert fake data into the database:

<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\Post;
use App\Models\Category;
use Illuminate\Support\Str;

class CreatePosts extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $cat1 = Category::create(['name' => 'Laravel']);
        $cat2 = Category::create(['name' => 'Laravel 11']);

        $posts = [
            [
                'title' => 'Laravel Product CRUD Tutorial',
                'body' => 'Step by Step Laravel Product CRUD Tutorial',
                'category_id' => $cat1
            ],
            [
                'title' => 'Laravel Image Upload Example',
                'body' => 'Step by Step Laravel Image Upload Example',
                'category_id' => $cat2
            ],
            [
                'title' => 'Laravel File Upload Example',
                'body' => 'Step by Step Laravel File Upload Example',
                'category_id' => $cat2
            ],
            [
                'title' => 'Laravel Cron Job Example',
                'body' => 'Step by Step Laravel Cron Job Example',
                'category_id' => $cat1
            ],
            [
                'title' => 'Laravel Send Email Example',
                'body' => 'Step by Step Laravel Send Email Example',
                'category_id' => $cat1
            ]
        ];

        foreach ($posts as $key => $value) {
            Post::create([
                'title' => $value['title'],
                'slug' => Str::slug($value['title']),
                'body' => $value['body'],
                'category_id' => $value['category_id'],
            ]);
        }
    }
}

Step 4 – Add Routes

Edit routes/web.php file, and add the routes in it that handle pagination with relation data requests:

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\PostController;
  
Route::get('posts', [PostController::class, 'index']);

Step 5 – Create Controller and Method

Run the following command to create a controller file that handle business logic in it:

php artisan make:controller PostController

Edit app/Http/Controllers/PostController.php file, and implement methods in it to handle pagination with relationship logic in it:

<?php
     
namespace App\Http\Controllers;
     
use Illuminate\Http\Request;
use App\Models\Post;
use Illuminate\Http\RedirectResponse;
     
class PostController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $posts = Post::with('category')->paginate(4);
  
        return view('posts', compact('posts'));
    }
}

Step 6 – Create Blade View

Go to resources/views directory and create a file named posts.blade.php that will show the pagination with relation data in an HTML table:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Laravel 11 Pagination with Relationship Tutorial - itcodStuff.com</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
</head>
<body>
      
<div class="container mt-5">
  
    <div class="card mt-5">
        <h3 class="card-header p-4">Laravel 11 Pagination with Relationship tutorial - itcodStuff.com</h3>
        <div class="card-body mt-4">
            <div class="row">
                @foreach($posts as $post)
                    <div class="col-md-3">
                        <div class="card mt-2" style="width: 18rem;">
                          <img src="https://picsum.photos/id/0/367/267" class="card-img-top" alt="...">
                          <div class="card-body">
                            <h5 class="card-title">{{ $post->title }}</h5>
                            <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
                            <button class="btn btn-primary">{{ $post->category->name ?? '' }}</button>
                          </div>
                        </div>
                    </div>
                @endforeach
            </div>

            <div class="mt-3">
                {{ $posts->links('pagination::bootstrap-5') }}
            </div>
        </div>
    </div>
</div>

</body>
</html>

Step 7 – Test This Application

Run the following command to start application server:

php artisan serve

Open browser and type http://localhost:8000/ url on browser to test this application.

Leave a Comment