@jeroenrosendaal You could, if you wanted swap the User $user with just $user and Post $post with $post. I usually don't type-hint those, or whatever. Also, Carbon::now() can just be written as now(). This is a global Laravel helper - I just think it looks cleaner. Not much else I'd say, if this works, that's all that really matters. This is perfectly readable to me. You could maybe cut down on some nesting by trading off some variables but it really doesn't make a big difference and would be slightly more code.
Jan 12, 2022
2
Level 11
Refactor Factory
Hi all,
I'm learning to use Factories and came up with the code below.
I would like to have your opinion about if this is the 'cleanest' way of writing it.
User::factory()->count(30)->create()->each(function(User $user) {
$user->posts()->saveMany(
Post::factory()
->count(10)
->create()
->each(function(Post $post) {
$category = Category::inRandomOrder()->first();
$post->categories()->attach($post->id,[
'category_id' => $category->id,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
]);
})
);
});
Please or to participate in this conversation.