magmatic's avatar

How to add a BelongsToMany related model in a factory if not specified?

I have two models that have a HasMany relationship pointing to each other (through a pivot table). Let's call them Post and Category.

Since I don't want any Posts to exist without at least one Category, I want to create a Category for it in its factory, using something like this in the Post factory.

	public function configure() {
		return $this->afterCreating(function (Post $post) {
			$post->categories()->attach(Category::factory()->create());
		});
	}

However, in a seeder, I might already have a Category that I want to use with a new Post. So I also want the option to pass in a Category into the Post factory, and not create a new Category, but instead attach the one given.

If this was a simple BelongsTo, it would be easy, but how do I do this with a HasMany?

I hope I described this right.

Thank you!

0 likes
1 reply
cookie's avatar
public function configure() {
    return $this->afterCreating(function (Post $post, $attributes) {
        $category = $attributes['category'] ?? Category::factory()->create();
        $post->categories()->attach($category);
    });
}

If you pass a category here it will be attached, otherwise it will create a new one.

$category = Category::find(1);
Post::factory()->create(['category' => $category]);

Please or to participate in this conversation.