If you can use factories for this, then use the following code
User Factory
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.
// Populate`teams` table with 6 entries
$teams = Team::factory->count(6)->create();
// Populate `users` table with 30 entries
$users = User::factory->count(30)->create();
// Now you need to populate `team_users` table.
// Assign 1 to 3 teams to each user (randomly)
$users->each(function ($user) use ($teams) {
$user->teams()->attach(
$teams->random(rand(1, 3))->pluck('id')->toArray()
);
});