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

voiceinthedark's avatar

Laravel factory generating excess records

I am trying to seed my database with fake records. My code works for any count number I specify with the correct relationships. However the factory seeder create random, excess records into the User model without any relationships, they're just dangling.

If I ask for a simple factory of count(1) it creates the record with the correct relationships needed, but then it adds like 3-5 extra fake users without any relationships...

What am I missing?

Here is my seeder code; this should produce 1 single user record with a single user profile with a random number of posts and its relationships; yet it creates more than 1:

public function run(): void
    { 

        // Run the seeders
        $this->call(RoleSeeder::class);
        $this->call(UserSeeder::class);
        $this->call(TagSeeder::class);
        $this->call(CategorySeeder::class);
        // $this->call(UserProfileSeeder::class);

        // Run the user factory
        User::factory()->create()->each(
            function ($user) {
                UserProfile::factory()->create([
                    'user_id' => $user->id
                ]);
                echo 'User ' . $user->id . ' created' . PHP_EOL;

                //user roles
                $user->roles()->attach(Role::where('name', 'user')->first());
                Post::factory(rand(1, 5))->create([
                    'user_id' => $user->id
                ])->each(function ($post) use ($user) {
                    $tags = Tag::all();
                    $categories = Category::all();
                    $post->tags()->attach($tags->random(rand(1, 3)));
                    $post->categories()->attach($categories->random(rand(1, 3)));
                    // echo 'User ' . $user->id . ' created' . PHP_EOL;
                });
            }
        );
    }
0 likes
1 reply
voiceinthedark's avatar

Nevermind It turned out I was creating addition users in the UserProfileSeeder as well as PostSeeder for the user_id field. Once I removed those fields, everything is working flawlessly.

Please or to participate in this conversation.