How to Create Pivot Table in Laravel: Step-by-Step Guide

Pivot Table in Laravel
Creating pivot tables in Laravel is essential for managing many-to-many relationships between database tables. This guide will walk you through the entire process, from setting up your environment to querying the pivot table.

Table of Contents

How to Set Up Your Laravel Project

Before you start, ensure you have Laravel installed. If not, follow these steps to create a new Laravel project:

Install Composer: Download and install Composer from getcomposer.org.
Create a Laravel Project: Run the following command to create a new project:

				
					composer create-project --prefer-dist laravel/laravel pivot-table-example
				
			

How to Create Models and Migrations

et’s create two models: Post and Tag. Each post can have multiple tags, and each tag can belong to multiple posts. We’ll start by generating the models and their migrations.

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

Defining the Tables

Next, define the tables in the migration files:

database/migrations/yyyy_mm_dd_create_posts_table.php

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

				
			

database/migrations/yyyy_mm_dd_create_tags_table.php

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

				
			

How to create the Pivot Table

To link posts and tags, create a pivot table migration:

				
					php artisan make:migration create_post_tag_table

				
			

Define the pivot table structure in the migration file:

database/migrations/yyyy_mm_dd_create_post_tag_table.php

				
					public function up()
{
    Schema::create('post_tag', function (Blueprint $table) {
        $table->id();
        $table->foreignId('post_id')->constrained()->onDelete('cascade');
        $table->foreignId('tag_id')->constrained()->onDelete('cascade');
        $table->timestamps();
    });
}

				
			

Run the migrations to create the tables:

				
					php artisan migrate
				
			

How to Define Relationships in Models

Define the relationships in the Post and Tag models.

app/Models/Post.php

				
					public function tags()
{
    return $this->belongsToMany(Tag::class);
}

				
			

app/Models/Tag.php

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

How to Insert Data into Pivot Tables

To associate tags with a post, use the attach method:

				
					$post = Post::find(1);
$tag = Tag::find(1);

$post->tags()->attach($tag);

				
			

For attaching multiple tags, use the sync method:

				
					$post->tags()->sync([1, 2, 3]);

				
			

How to Query Pivot Tables in Laravel

Retrieve all tags associated with a post:

				
					$post = Post::find(1);
$tags = $post->tags;

foreach ($tags as $tag) {
    echo $tag->name;
}

				
			

Retrieve all posts associated with a tag:

				
					$tag = Tag::find(1);
$posts = $tag->posts;

foreach ($posts as $post) {
    echo $post->title;
}

				
			

Conclusion

Creating pivot tables in Laravel is straightforward and essential for managing many-to-many relationships. By following this guide, you can set up, use, and query pivot tables efficiently in your Laravel projects. If you have any questions or need further assistance, feel free to reach out. Happy coding!

Written By,

Picture of Md Monayem Islam

Md Monayem Islam

Hey, I'm Md Monayem Islam. I’m a Full Stack Developer with extensive expertise in Laravel (PHP), Vue.js (TypeScript), and API development. Over the years, I’ve honed my skills in building dynamic and scalable web applications. Previously, I worked on a variety of projects, creating robust solutions and enhancing the user experience for clients worldwide. Now, I’m here to share my knowledge and help you develop web applications.

Want a FREE Consultation?

I am here to assist with your queries. Schedule now!
Share the Post:

Let's Connect!

Have a question? Contact me and I’ll get back to you soon.

Do you Need a developer for your project?