Laravel - Seeding Many-to-Many Relationship
Stefan Bogdanescu
Founder & Senior Architect · 2026-06-29
Populating Many-to-Many Relationships with Laravel Seeding
In this post, we'll discuss how to populate a many-to-many relationship between two tables when seeding data in your Laravel project. We will focus on the example of seeding users and roles with their corresponding junction table, role_user. To start, let's first create the necessary models for users and roles: For your User model, add the following code to implement many-to-many relationships with roles and other entities:php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function roles()
{
return $this->belongsToMany('App\Role');
}
}php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
public function users()
{
return $this->belongsToMany('App\User');
}
}php
$factory->define(App\User::class, function (Faker\Generator $faker) {
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'password' => $password ?: $password = bcrypt('secret'),
];
});php
$factory->define(App\Role::class, function (Faker\Generator $faker) {
return [
'role' => $faker->realText($maxNbChars = 2),
'description' => $faker->realText($maxNbChars = 20),
];
});php
public function run()
{
factory(App\User::class, 50)->create()->each(function ($u) {
$u->roles()->save(factory(App\Role::class)->make());
});
factory(App\Role::class, 20)->create()->each(function ($u) {
$u->users()->save(factory(App\User::class)->make());
});
}shell
php artisan migrate:refresh --seed