I want to run seeders for tables users
, courses
and `episodes.
Here is UserFactory
:
public function definition()
{
static $password;
return [
'name' => $this->faker->name,
'email' => $this->faker->unique()->safeEmail,
'password' => $password ?: $password = bcrypt('secret'),
'remember_token' => Str::random(10),
];
}
And here is EpisodeFactory
:
public function definition()
{
return [
'title' => $this->faker->sentence(),
'body' => $this->faker->paragraph(5),
'videoUrl' => 'https://www.quirksmode.org/html5/videos/big_buck_bunny.mp4',
];
}
And this is CourseFactory
:
public function definition()
{
return [
'title' => $this->faker->sentence(),
'body' => $this->faker->paragraph(5),
'price' => $this->faker->numberBetween(1000,10000),
'image' => $this->faker->imageUrl(),
];
}
Then I added this to the DatabaseSeeder
:
public function run()
{
$user = \App\Models\User::factory()->count(30)->create();
\App\Models\Course::factory()->count(5)->create(['user_id' => $user->id ])->each(function ($course) {
\App\Models\Episode::factory()->count( rand(6 , 20))->make()->each(function ($episode , $key) use ($course){
$episode->number = $key +1;
$course->episodes()->save($episode);
});
});
}
Now when I run php artisan db:seed
, I get this error:
Exception Property [id] does not exist on this collection instance.
Which is referring to create(['user_id' => $user->id ])
at DatabaseSeeder
.
So what's going wrong here? How can I solve this issue?
And here is also the Migration of users
table:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Also if you need any other Migration or Model codes to look at, just let me know, I will add them immediately.