Laravel factory state method is only run once for multiple models

751 Views Asked by At

Working with Laravel 9, I have a state method in my factory defined similar to this:

class PostFactory extends Factory
{
    public function definition(): array
    {
        return [
            "user" => User::factory(),
            "title" => $this->faker->bs(),
            "content" => $this->faker->text(1000),
        ];
    }

    public function tagged(): self
    {
        return $this->state(["tag" => $this->faker->word()]);
    }
}

I would like to generate some users who have some tagged posts. But when I try to generate models with this syntax:

$users = User::factory()
    ->has(Post::factory()->tagged()->count(5), "posts")
    ->count(5)
    ->create();

The state method PostFactory::tagged() is only called once (confirmed with debug output in the method) and all 25 posts (5 for each user) have the same tag. I would like each post to have a unique tag. Is there a straightforward way to do this without manually changing them after creation?

0

There are 0 best solutions below