First, ensure you have your factory definitions like this.
UserFactory
class UserFactory extends Factory
{
protected $model = User::class;
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),
'team_id' => Team::factory()->create()->id
];
}
}
TeamFactory
class TeamFactory extends Factory
{
protected $model = Team::class;
public function definition()
{
return [
'name' => $this->faker->name
];
}
}
There are two ways to go about this.
Approach 1
User::factory()->count(5)->create();
But in this example if you create 5 users, then 5 different teams will be created and every user will be assigned to one team. I assume this is not what you would normally want.So to work around this, you can do something like this.
Approach 2
Here you will be creating 5 users by overriding the team_id column for all users. So all new users will belong to one team
// create 5 users and assign to the same team
$users = User::factory()->count(5)->create([
'team_id' => Team::factory()->create()->id
])
Docs
https://laravel.com/docs/8.x/database-testing#factory-relationships