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

P-James's avatar
Level 12

Seeding Users with Teams in Laravel 8 and Jetstream

Is there a way I can run something like this in my seeder, passing the user_id instead of ???

$users = User::factory()
            ->hasTeams(1, [
                'user_id' => ???,
            ])
            ->create();

I have already set up my TeamFactory, another option would eb to pass the user_id to the TeamFactory class somehow.

Any ideas?

0 likes
5 replies
P-James's avatar
P-James
OP
Best Answer
Level 12

Ok I'm feelign stupid, the solution is of course in the TeamFactory:

public function definition()
    {
        return [
            'user_id' => User::factory()->create(),
            'name' => $this->faker->words(2, true),
            'personal_team' => true,
        ];
    }

And seed the teams, not the users. I tried this first but got an error..

Remember to add the HasFactory trait to the Team Model!

5 likes
fahmidotexe's avatar

@P-James Hi, I know this is old thread, but can you give me an example how you do it? I still not getting it. Thanks!

P-James's avatar
Level 12

@fahmidotexe Can you paste your seeder and factories that you're running? The premise is replace the foreign key in the factory, eg user_id, with a model.

jmacdiarmid's avatar

I'm working on a Laravel 9 project with Jetstream and setting up Spatie Permissions package. The following code worked for me. Hopefully it will help someone else looking to do something similar. I have this code in my UserTableSeeder class.

public function run()
    {
        $user =  User::create([
   		     // populate user fields
        ]);

		// This code is taken from "App\Actions\Fortify\CreateNewUser.php" 
        $user->ownedTeams()->save(Team::forceCreate([
            'user_id' => $user->id,
            'name' => explode(' ', $user->name, 2)[0]."'s Team",
            'personal_team' => true,
        ]));
    }

Please or to participate in this conversation.