Laravel 11 Pagination with Relationship Example Tutorial

Jun 15, 2024 | Laravel 11 Laravel


Hello Dev,

In this post, we'll explore how to implement paginated results with relationships in a Laravel 11 application.

In our example, we'll set up two tables: `posts` and `categories`. We'll establish a "has many" relationship in the `Category` model to link it with posts using the `hasMany` method, and a "belongs to" relationship in the `Post` model to connect each post with its category using the `belongsTo` method. Following this, we'll populate the database with sample data using Seeder commands. Subsequently, we'll demonstrate how to paginate the posts while including related category data. By default, Laravel pagination uses Tailwind CSS for design, but we'll customize it to use Bootstrap 5 for pagination.

This tutorial will guide you through each step, ensuring you can effectively display paginated posts with their corresponding category information in your Laravel 11 application.

Step 1: Install Laravel 10

If you haven't already, create a new Laravel project:

composer create-project laravel/laravel example-app
Step 2: Create Category and Post Table

Here, we will generate the categories and posts tables along with their respective models. Let's execute the following command:

php artisan make:migration create_categories_table
php artisan make:migration create_posts_table

now, let's update the following migrations:

database/migrations/2024_06_11_035146_create_posts_table.php
<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    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();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('posts');
    }
};
database/migrations/2024_06_13_175106_create_categories_table.php
<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('categories');
    }
};

now, Let's run the migration command:

php artisan migrate
Read Also: How to Send Whatsapp Message Using Laravel 11? Step 3: Create Category and Post Model

Here, we will create the `Category` and `Post` models using the following command:

php artisan make:model Category
php artisan make:model Post

These commands will generate the `Category` and `Post` models in your Laravel 11 application.

app/Models/Category.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Category extends Model
{
    use HasFactory;

    /**
     * Write code on Method
     *
     * @return response()
     */
    protected $fillable = [ 'name' ];

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function posts(): HasMany
    {
        return $this->hasMany(Post::class);
    }
}
app/Models/Post.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Post extends Model
{
    use HasFactory;

    /**
     * Write code on Method
     *
     * @return response()
     */
    protected $fillable = [
        'title', 'body', 'slug', 'category_id'
    ];

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function category(): BelongsTo
    {
        return $this->belongsTo(Category::class);
    }
}
Step 4: Create Dummy Category and Posts

In this step, we need to run the migration command to create the seeder files for populating dummy records in the categories and posts tables.

First, let's generate the seeder for posts:

php artisan make:seeder CreatePosts

Next, we'll update the `CreatePosts` seeder file to define the logic for seeding data into the categories and posts tables.

database/seeders/CreatePosts.php
<?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 5: Add Route

To begin, we will define a route specifically for listing posts with pagination and their related data. Add the following routes individually in your route file:

routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\PostController;
  
Route::get('posts', [PostController::class, 'index']);
Read Also: Laravel 11 JSON Web Token(JWT) API Authentication Example Tutorial Step 6: Create Controller

Similarly, for the "route" method in the PostController, we'll add a new method called index() that returns paginated posts data. Here's how to implement it:

app/Http/Controllers/PostController.php
<?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 7: Create Blade File

In this step, you'll create a posts.blade.php file and include the following code, along with the links() method to automatically generate pagination:

resources/views/posts.blade.php
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Laravel 11 Pagination with Relationship Example Tutorial -- ItErrorSolution.com</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css">
</head>
<body>
      
<div class="container mt-5">
  
    <div class="card mt-5">
        <h3 class="card-header p-3">Laravel 11 Pagination with Relationship Example Tutorial -- ItErrorSolution.com</h3>
        <div class="card-body mt-3">
            <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: Run the Application

Now, to run the Laravel application, please type the following command and press enter:

php artisan serve
http://localhost:8000/posts
Output: Laravel 11 Pagination with Relationship Example Tutorial

Feel free to ask if you have any questions or need further clarification!



Tags :
#Laravel 11
#Laravel
ItErrorSolution.com

ItErrorSolution.com

"Hey there! I'm a full-stack developer and proud owner of ItErrorSolution.com, based right here in India. I love nothing more than sharing handy tips and tricks with my fellow developers through easy-to-follow tutorials. When it comes to coding, I'm all about PHP, Laravel, Angular, Vue, Node, JavaScript, jQuery, CodeIgniter, and Bootstrap – been hooked on them forever! I'm all about putting in the work and staying committed. Ready to join me on this journey to coding?"