Reputation: 1698
I have Users
and UserProfiles
.
All Users
have one and only one UserProfile
.
My UserTableSeeder
class is creating 25 records and for each record, outputting a UserProfile
.
For some reason, I am getting double the records on Users
and the amount specified on UserProfile
So 50 Users
are being inserted and 25 UserProfiles
are being inserted.
Seed:
public function run()
{
factory(App\User::class, 25)->create()->each(function ($user) {
$user->profile()->save(factory(App\UserProfile::class)->make());
});
}
User Class:
class User extends Model
{
public function profile() {
return $this->hasOne('App\UserProfile');
}
}
UserFactory:
$factory->define(User::class, function (Faker $faker) {
return [
'username' => $faker->userName(),
'email' => $faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
'remember_token' => Str::random(10),
];
});
UserProfileFactory:
$factory->define(UserProfile::class, function (Faker $faker) {
return [
'user_id' => factory('App\User'::class)->create()->id,
'bio' => $faker->paragraph()
];
});
UserProfile Model:
class UserProfile extends Model
{
public function user() {
return $this->belongsTo('App\User');
}
}
My expected output was 25 users and 25 users table since all users have a profile
Upvotes: 2
Views: 844
Reputation: 8618
Change this code
$factory->define(UserProfile::class, function (Faker $faker) {
return [
'user_id' => factory('App\User'::class)->create()->id,
'bio' => $faker->paragraph()
];
});
To
$factory->define(UserProfile::class, function (Faker $faker) {
return [
'bio' => $faker->paragraph()
];
});
Upvotes: 2