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

Laravel where and orWhere Condition Example


how to use where and orwhere condition in laravel 8, laravel 8 where and orwhere condition, where and orwhere laravel 8 example, orwhere and where in...

Laravel 9 Generate Sitemap XML File Tutorial


Learn how to generate a sitemap.xml file in Laravel 9 with this step-by-step tutorial. Improve your website's SEO and enhance user experience.

Laravel Google Chart Example Tutorial


laravel google chart example, dynamic charts in laravel, laravel google pie chart, laravel google line chart example, google chart in laravel, laravel...

How To Use WYSIHTML5 Editor In Laravel 9?


wysihtml5 editor example, laravel wysihtml5 editor example, wysihtml5 laravel, wysihtml5 editor example in laravel, wysihtml5 with laravel, wysihtml5...

Laravel Many to Many Polymorphic Relationship


Laravel many to many polymorphic relations, many to many polymorphic relations Laravel, polymorphic relations eloquent Laravel, Laravel morphToMany ex...