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;
}