Laravel 11 Pagination with Relationship
Laravel 11 Pagination with Relationship

Laravel 11 Pagination with Relationship Example

Laravel, a popular PHP framework, makes it easy to handle pagination with relationships in your database queries. This tutorial will guide you through a step-by-step process to implement pagination with relationships in Laravel 11.

What is Pagination?

Pagination is a technique to split large datasets into smaller, manageable chunks. Instead of loading thousands of records at once, pagination allows us to load a fixed number of records per page.

Setting Up Laravel

First, ensure you have Laravel installed. If not, you can create a new Laravel project using Composer:

composer create-project --prefer-dist laravel/laravel laravel11pagination

Navigate into your project directory:

cd laravel11pagination

Creating Models and Migrations

For this example, we will create two models: Post and Comment. Each post can have multiple comments.

Create the Post model and migration:

php artisan make:model Post -m

Create the Comment model and migration:

php artisan make:model Comment -m

Defining Database Schema

Open the generated migration files and define the schema.

In database/migrations/xxxx_xx_xx_create_posts_table.php:

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

In database/migrations/xxxx_xx_xx_create_comments_table.php:

public function up()
{
    Schema::create('comments', function (Blueprint $table) {
        $table->id();
        $table->foreignId('post_id')->constrained()->onDelete('cascade');
        $table->string('author');
        $table->text('content');
        $table->timestamps();
    });
}

Run the migrations to create the tables in your database:

php artisan migrate

Defining Relationships

Define the relationships in your models. In app/Models/Post.php:

namespace App\Models;

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

class Post extends Model
{
    use HasFactory;

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

In app/Models/Comment.php:

namespace App\Models;

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

class Comment extends Model
{
    use HasFactory;

    public function post()
    {
        return $this->belongsTo(Post::class);
    }
}

Seeding Data

Let’s seed some data to test our pagination. Create a seeder file:

php artisan make:seeder DatabaseSeeder

In database/seeders/DatabaseSeeder.php:

use Illuminate\Database\Seeder;
use App\Models\Post;
use App\Models\Comment;

class DatabaseSeeder extends Seeder
{
    public function run()
    {
        Post::factory(10)->create()->each(function ($post) {
            Comment::factory(10)->create(['post_id' => $post->id]);
        });
    }
}

Run the seeder:

php artisan db:seed

Implementing Pagination

Now, let’s implement pagination in a controller. Create a new controller:

php artisan make:controller PostController

In app/Http/Controllers/PostController.php:

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function index()
    {
        $posts = Post::with('comments')->paginate(5); // 5 posts per page
        return view('posts.index', compact('posts'));
    }
}

Creating a View

Create a Blade view to display the posts and their comments. Create a new view file at resources/views/posts/index.blade.php:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 11 Pagination with Relationships</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <h1>Posts</h1>
    @foreach ($posts as $post)
        <div class="card mb-3">
            <div class="card-body">
                <h5 class="card-title">{{ $post->title }}</h5>
                <p class="card-text">{{ $post->body }}</p>
                <h6>Comments:</h6>
                @foreach ($post->comments as $comment)
                    <p><strong>{{ $comment->author }}:</strong> {{ $comment->content }}</p>
                @endforeach
            </div>
        </div>
    @endforeach
    {{ $posts->links() }}
</div>
</body>
</html>

Defining Routes

Finally, define a route to access the posts. In routes/web.php:

use App\Http\Controllers\PostController;

Route::get('/posts', [PostController::class, 'index']);

Testing the Pagination

Start the Laravel development server:

php artisan serve

Visit http://localhost:8000/posts in your web browser. You should see a list of posts with their comments, paginated.

Conclusion

You’ve now implemented pagination with relationships in Laravel 11. This example demonstrated how to create models, define relationships, seed data, and paginate results. This technique helps manage large datasets efficiently, enhancing the user experience.