Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

FutureWeb's avatar

Model factory belongsToMany relations

Hi LaraPeeps!

I have the standard user model factory

 public function definition()
    {
        return [
            'name' => $this->faker->name,
            'email' => $this->faker->unique()->safeEmail,
            'email_verified_at' => now(),
            'password' => 'yIXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
            'remember_token' => Str::random(10),
        ];
    }

A user belongs to many roles through a pivot table all relations are set up and working my question is how in tinker do I create 10 users and assign them to a role with an ID of 2 using the model factory?

0 likes
1 reply
kevinbui's avatar
kevinbui
Best Answer
Level 41

Maybe you can simply do this:

$role = Role::find(2);

$users = User::factory()
    ->count(10)
    ->create()
    ->each(function ($user) use ($role))
    {
        $user->roles()->attach($role->id);
    }

Regarding the documentation, apparently we can also do this:

$role = Role::find(2);

$user = User::factory()
            ->count(3)
            ->hasAttached($role)
            ->create();
2 likes

Please or to participate in this conversation.