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?
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();
Please sign in or create an account to participate in this conversation.