How to Create Pivot Table in Laravel: Step-by-Step Guide
In Laravel, create a pivot table by defining a many-to-many relationship using
belongsToMany in your models and creating a migration for the pivot table with foreign keys. Use attach, detach, or sync methods to manage related records through the pivot table.Syntax
To create a pivot table in Laravel, you need to:
- Create a migration for the pivot table with foreign keys referencing the related tables.
- Define a
belongsToManyrelationship in both related Eloquent models. - Use Eloquent methods like
attach,detach, orsyncto manage the pivot table records.
php
<?php // In migration file for pivot table Schema::create('role_user', function (Blueprint $table) { $table->id(); $table->foreignId('user_id')->constrained()->onDelete('cascade'); $table->foreignId('role_id')->constrained()->onDelete('cascade'); $table->timestamps(); }); // In User model public function roles() { return $this->belongsToMany(Role::class); } // In Role model public function users() { return $this->belongsToMany(User::class); }
Example
This example shows how to create a pivot table between User and Role models, attach roles to a user, and retrieve them.
php
<?php // Migration for pivot table use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateRoleUserPivotTable extends Migration { public function up() { Schema::create('role_user', function (Blueprint $table) { $table->id(); $table->foreignId('user_id')->constrained()->onDelete('cascade'); $table->foreignId('role_id')->constrained()->onDelete('cascade'); $table->timestamps(); }); } public function down() { Schema::dropIfExists('role_user'); } } // User.php model namespace App\Models; use Illuminate\Database\Eloquent\Model; class User extends Model { public function roles() { return $this->belongsToMany(Role::class); } } // Role.php model namespace App\Models; use Illuminate\Database\Eloquent\Model; class Role extends Model { public function users() { return $this->belongsToMany(User::class); } } // Usage example in controller or tinker $user = User::find(1); $user->roles()->attach([1, 2]); // Attach roles with IDs 1 and 2 $roles = $user->roles; // Retrieve roles foreach ($roles as $role) { echo $role->name . "\n"; }
Output
Admin
Editor
Common Pitfalls
Common mistakes when creating pivot tables in Laravel include:
- Not creating the pivot table migration or missing foreign keys.
- Forgetting to define
belongsToManyrelationships in both models. - Using incorrect pivot table name or column names that don't follow Laravel conventions.
- Trying to access pivot data without specifying
withPivotif you have extra columns.
php
<?php // Wrong pivot table name example // Laravel expects pivot table named alphabetically: role_user, not user_role // Wrong way public function roles() { return $this->belongsToMany(Role::class, 'user_role'); // Incorrect table name } // Right way public function roles() { return $this->belongsToMany(Role::class, 'role_user'); } // Accessing extra pivot columns public function roles() { return $this->belongsToMany(Role::class)->withPivot('expires_at'); }
Quick Reference
Summary tips for pivot tables in Laravel:
- Pivot table name: combine related table names alphabetically (e.g.,
role_user). - Pivot table columns: include foreign keys and timestamps if needed.
- Define
belongsToManyin both models. - Use
attach,detach, andsyncto manage relations. - Use
withPivotto access extra pivot columns.
Key Takeaways
Create a pivot table migration with foreign keys for many-to-many relationships.
Define belongsToMany relationships in both related models.
Use attach, detach, and sync methods to manage pivot table records.
Name pivot tables alphabetically combining related table names.
Use withPivot to access extra columns on the pivot table.