Laravel 9 Many To Many Relationship Example

Websolutionstuff | Apr-03-2022 | Categories : Laravel PHP

In this article, we will see laravel 9 many to many relationship example. Also, you can use many to many relationships in laravel 6 and laravel 7 and laravel 8. Many to many relationships is more complicated than one to one and one to many relationships. An example of like a relationship is a user with have multiple roles, where the role are also connected with multiple users.

So, let's see many to many relationship in laravel 9, laravel 9 eloquent relationships example, laravel 9 hasMany example, many to many relationship laravel 9.

Also, we will create migration with a foreign key, sync with a pivot table, retrieve records using the model, insert new records, update records, etc. We will create a User and Roles and Role_users table. all tables are connected with each other table. Now we will create many to many relationships with each other by using the laravel Eloquent Model.

laravel_9_many_to_many_relationship

Create Migration

Now, we have to create migration for users and roles and role_users table. we will also add foreign keys with the users and roles table.

Create Migration of Users Table

Schema::create('users', function (Blueprint $table) {

    $table->increments('id');

    $table->string('name');

    $table->string('email')->unique();

    $table->timestamps();

});

 

 

Create Migration of Roles Table

Schema::create('roles', function (Blueprint $table) {

    $table->increments('id');

    $table->string('name');

    $table->timestamps();

});

Create Migration of Role Users Table

Schema::create('role_users', function (Blueprint $table) {

    $table->integer('user_id')->unsigned();

    $table->integer('role_id')->unsigned();

    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

    $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');

});

 

Create Model and Add Relationship on Both Model

Now, we will create a User, Role model. we will use the belongsToMany() relationship for both models.

User Model :

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get the phone associated with the user.
     */
    public function roles()
    {
        return $this->belongsToMany(Role::class, 'role_users');
    }
}

 

 

Role Model :

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{    
    public function user()
    {
        return $this->belongsToMany(User::class, 'role_users');
    }
}

 

Retrieve Records using Model :

Once the relationship is defined, we may retrieve the related record using Eloquent's dynamic properties.

$role = User::find(1)->roles;
$user = Role::find(1)->users;

 

 

Create Records using Model 

In this step, we will create records in the role tables. 

$user = User::find(1);	
 
$role_ids = [1, 2];
$user->roles()->attach($role_ids);
$user = User::find(3);	
 
$role_ids = [1, 2];
$user->roles()->sync($role_ids);

 


You might also like :

Recommended Post
Featured Post
Laravel 9 whereDate And whereMonth Query Example
Laravel 9 whereDate And whereM...

In this article, we will see laravel 9 wheredate() and wheremonth() query examples. The whereDate me...

Read More

Oct-19-2022

How to Install PHP JSON Extension in Ubuntu 23.04
How to Install PHP JSON Extens...

Hey there! If you're working with PHP on Ubuntu 23.04 and find yourself needing JSON support, you're in the righ...

Read More

Feb-05-2024

How To Block IP Address In Laravel 10
How To Block IP Address In Lar...

In this article, we will see how to block IP addresses in laravel 10. Here we will learn about how to restrict...

Read More

May-17-2023

How To Create Pie Chart In Laravel 9 Using Highcharts
How To Create Pie Chart In Lar...

In this article, we will see how to create a pie chart in laravel 9 using highcharts. A pie chart is a circular statisti...

Read More

Oct-05-2022