Laravel 9 Many to Many Relationship Example

Many to many relationships are very common in web applications. For example, a user may have many roles, and a role may have many users.

In this example, we will create a many to many relationship between users and roles.

First, we will create a User model and a Role model.

User Model

belongsToMany(‘App\Role’);
}
}

Role Model

belongsToMany(‘App\User’);
}
}

Next, we will create a pivot table to store the many to many relationship.

php artisan make:migration create_role_user_table

bigIncrements(‘id’);
$table->unsignedBigInteger(‘user_id’);
$table->unsignedBigInteger(‘role_id’);
$table->timestamps();
});
}

public function down()
{
Schema::dropIfExists(‘role_user’);
}
}

Finally, we can create a seeder to populate the database with some dummy data.

‘admin’,
]);
$userRole = Role::create([
‘name’ => ‘user’,
]);

// Create users
$adminUser = User::create([
‘name’ => ‘Admin User’,
’email’ => ‘[email protected]’,
‘password’ => bcrypt(‘password’),
]);
$regularUser = User::create([
‘name’ => ‘Regular User’,
’email’ => ‘[email protected]’,
‘password’ => bcrypt(‘password’),
]);

// Assign roles to users
$adminUser->roles()->attach($adminRole);
$regularUser->roles()->attach($userRole);
}
}

Now, we can run the seeder to populate the database with the dummy data.

php artisan db:seed –class=RoleUserTableSeeder

Laravel 9 many to many relationship example; In this tutorial, you will learn laravel many to many relationship with examples.

Using belongsToMany() method, you can define many to many relationship in laravel eloquent models. And you can also insert, update and delete records from database table using many to many relationship in laravel

Laravel Eloquent Many to Many Relationship Example

In this example, you will see two tables name posts and tags.

Each post has many tags and each tag can have many posts.

To define many to many relationships, Using belongsToMany() method:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
   ...
    public function tags()
    {
        return $this->belongsToMany('App\Tag');
    }
}

To access the tags in the post model as follow:

$post = App\Post::find(8);

 foreach ($post->tags as $tag) {
    //do something
 }

The inverse of Many to Many Relationship Example

The inverse of a many to many relationships can be defined by simply calling the similar belongsToMany method on the reverse model. We can illustrate that by defining posts() method in Tag model as:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tag extends Model
{
    public function posts()
    {
        return $this->belongsToMany('App\Post');
    }
}

To access the post in the tag model as follow:

$tag = App\Tag::find(8);

 foreach ($tag->posts as $post) {
     //do something
  }

Conclusion

In this tutorial, you have learned define many to many relationships and as well as how to use it.

Recommended Laravel Tutorials

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

Contact
San Vito Al Tagliamento 33078
Pordenone Italy
Item added to cart.
0 items - 0.00
Open chat
Scan the code
Hello 👋
Can we help you?