One-to-one and one-to-many connections are more intricate than many-to-many relationships. A user with numerous roles, each of which is related to many users, is an example of such a relationship. In Laravel 6, Laravel 7, Laravel 8, and Laravel 9, there are many to many relationships.
So, in this tutorial, you'll learn how to create many-to-many relationships using migration and a foreign key schema for one-to-many relationships, as well as how to use sync with a pivot table, create records, attach records, get all records, delete, update, and everything else related to many-to-many relationships.
In this example, I'll construct tables for "users," "roles," and "role user." Each table is linked to the others. Using the Laravel Eloquent Model, we will now construct many to many relationships with each other. We'll start with database migration, then move on to modelling, retrieving records, and finally creating records.

The relation "belongsToMany()" will be used in the Many to Many Relationship.

1. Create Migrations

Now we must migrate the tables "users," "roles," and "role user." With the users and roles table, we'll also add a foreign key. So, let's make something similar to what's seen here.

users table migration
Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('email')->unique();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});
 
roles table migration
Schema::create('roles', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->timestamps();
});
 
role_user table migration
Schema::create('role_user', 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');
});

 

2. Create Models

The User, Role, and UserRole table models will be created here. For the relationship between the two models, we'll utilise "belongsToMany()"

 
User Model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
    use Notifiable;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
     /**
     * The roles that belong to the user.
     */
    public function roles()
    {
        return $this->belongsToMany(Role::class, 'role_user');
    }
}
?>
 
Role Model
<?php
 namespace App;
 use Illuminate\Database\Eloquent\Model;
 class Role extends Model
{
    /**
     * The users that belong to the role.
     */
    public function users()
    {
        return $this->belongsToMany(User::class, 'role_user');
    }
}
?>
 
UserRole Model
<?php
 namespace App;
 use Illuminate\Database\Eloquent\Model;
 class UserRole extends Model
  {
  }
?>

 

3. Retrieve Records

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

 

4. Create 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 will like the content and it will help you to learn Laravel Many to Many Eloquent Relationship
If you like this content, do share.


Recommended Posts

View All

TOP PROGRAMMING LANGUAGES TO GET A JOB AT GOOGLE, MICROSOFT AND FACEBOOK


It's an available fact that if you want to work at the big tech companies, you need to know how to make an impression.

How to Use Yajra Datatables in Laravel 9 Application


Learn how to enhance your Laravel 9 application with Yajra Datatables. This tutorial will guide you through the steps of integrating and using it.

Most Important Array Methods in JavaScript


Learn the most important array methods in JavaScript, including push, pop, shift, unshift, forEach, map, filter, reduce, and find. Improve your coding...

Laravel 8 Collection with first() and firstWhere() Methods Example


You'll learn how to use the first() and firstWhere() methods in Laravel 8 Collection. The Laravel collection will make working with arrays much easier

Laravel Eloquent WHERE Like Query Example Tutorial


Laravel provides a query builder that helps us to deal with such a situation in MySQL. In this tutorial, you'll learn how to use a select where like q...