I want to test my database and I have made factories and the following is my code inside my seeder file
public function run()
{
Category::factory()->count(10)->create();
User::factory()
->has(Profile::factory()->state(function (array $attributes, User $user) {
return ['user_id' => $user->id];
}))
->has(Post::factory()->count(50)
->state(function (array $attributes, User $user, Category $category) {
return ['user_id' => $user->id, 'category_id' => $category->id];
})
->has(Comment::factory()->count(3))
->state(function (array $attributes, User $user, Post $post) {
return ['user_id' => $user->id, 'category_id' => $post->id];
}))
->create();
}
I want to make some categories and 1 or more users with attached profiles, posts and comments. Can someone please check if my code is correct because it is giving the following error:
Too few arguments to function Database\Seeders\DatabaseSeeder::Database\Seeders{closure}(), 2 passed in D:\xampp\htdocs\blog\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Factories\Factory.php on line 422 and exactly 3 expected
at D:\xampp\htdocs\blog\database\seeders\DatabaseSeeder.php:28 24▕ ->has(Profile::factory()->state(function (array $attributes, User $user) { 25▕ return ['user_id' => $user->id]; 26▕ })) 27▕ ->has(Post::factory()->count(50) ➜ 28▕ ->state(function (array $attributes, User $user, Category $category) { 29▕ return ['user_id' => $user->id, 'category_id' => $category->id]; 30▕ }) 31▕ ->has(Comment::factory()->count(3)) 32▕ ->state(function (array $attributes, User $user, Post $post) {
1
D:\xampp\htdocs\blog\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Factories\Factory.php:422 Database\Seeders\DatabaseSeeder::Database\Seeders{closure}(Object(App\Models\User))2
D:\xampp\htdocs\blog\vendor\laravel\framework\src\Illuminate\Collections\Traits\EnumeratesValues.php:741 Illuminate\Database\Eloquent\Factories\Factory::Illuminate\Database\Eloquent\Factories{closure}(Object(Closure))
There is a problem with your second and third closure:
->state(function (array $attributes, User $user, Category $category)
You cannot expect more than $attributes
and created parent model ($user
in this case). This $category
parameter causes the problem, you need to acquire this object outside closure.