Many to Many Eloquent Relationship Laravel Tutorial

Hi Guys,
In this tutorial, we will see how to use many to many relationship in Laravel 9 with an example. Many to many relationship is a little bit complicated than one to one and one to many relationships. Laravel many to many eloquent relationship; Through this tutorial, i am going to show you what is many to many relationship and how to use many to many relationship in laravel 9 application. An example of a many-to-many relationship is a user that has many roles and those roles are also shared by other users in the application.
So in this tutorial, you can understand how to create many-to-many relationships with migration with a foreign key schema for one to many relationships, use sync with a pivot table, create records, attach records, get all records, delete, update, where condition and everything related to many to many relationship.
In this example, i will create "users", "roles" and "role_user" tables. each table is connected with each other. now we will create many to many relationships with each other by using the laravel Eloquent Model. We will first create database migration, then model, retrieve records and then how to create records too. So you can also see database table structure on below screen.
Laravel 9 many to many relationship is slightly more complicated than hasOne and hasMany relationships.
So, let's start following example:
Step 1: Download Laravel Let us begin the tutorial by installing a new laravel application. if you have already created the project, then skip following step.composer create-project laravel/laravel example-appStep 2: Add Migrations:
Now we have to create migration of "users", "roles" and "role_user" table. we will also add foreign key with users and roles table. so let's create like as below:
database\migrations\2014_10_12_000000_create_users_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. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } };roles table migration:
php artisan make:migration create_roles_tabledatabase\migrations\2014_10_12_000000_create_roles_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. * * @return void */ public function up() { Schema::create('roles', function (Blueprint $table) { $table->id(); $table->string('name'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('roles'); } };role_user table migration:
php artisan make:migration create_role_user_tabledatabase\migrations\2014_10_12_000000_create_role_user_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. * * @return void */ public function up() { Schema::create('role_user', function (Blueprint $table) { $table->foreignId('user_id')->constrained('users'); $table->foreignId('role_id')->constrained('roles'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('role_user'); } };Step 3: Add Models
Here, we will create User, Role and UserRole table model. we will also use "belongsToMany()" for relationship of both model.
app\Http\Model\User.php<?php namespace App\Models; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for serialization. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast. * * @var array */ protected $casts = [ 'email_verified_at' => 'datetime', ]; /** * The roles that belong to the user. */ public function roles() { return $this->belongsToMany(Role::class, 'role_user'); } }Role Model:
php artisan make:model Roleapp\Http\Model\Role.php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Role extends Model { use HasFactory; /** * The users that belong to the role. */ public function users() { return $this->belongsToMany(User::class, 'role_user'); } }UserRole Model:
php artisan make:model UserRoleapp\Http\Model\UserRole.php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class UserRole extends Model { use HasFactory; }Step 4: Retrieve Records:
$user = User::find(1); dd($user->roles);
$role = Role::find(1); dd($role->users);Step 5: Add Records:
$user = User::find(2); $roleIds = [1, 2]; $user->roles()->attach($roleIds);
$user = User::find(3); $roleIds = [1, 2]; $user->roles()->sync($roleIds);
$role = Role::find(1); $userIds = [10, 11]; $role->users()->attach($userIds);
$role = Role::find(2); $userIds = [10, 11]; $role->users()->sync($userIds);
I hope you understand of many to many relationship...
Divyang Vadodariya
My name is Divyang Vadodariya. I'm a full-stack developer, entrepreneur and owner of RvSolutionStuff. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap ,etc from the early stage.

We are Recommending you
- Error: Class "App\Http\Controllers\Validator" not found
- Laravel Google Maps Multiple Markers Example
- How to Http Curl Delete Request in Laravel?
- How to Get Array of Ids from Eloquent Models in Laravel?
- How to Use the WHERE Clause in PHP MySQL?
- Reverse List Elements in Python Example
- How to Display Average Of All Rows In Column of PHP MySQL?
- How to Get the Sum of Column in PHP MySQL?
- Many to Many Eloquent Relationship Laravel Tutorial
- One to Many Polymorphic Eloquent Relationship Laravel Toturial
Copyright © 2023 www.RVSolutionStuff.com • All Rights Reserved