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]);