0

since this "new" update came in laravel (laravel 8) I am struggling with factories. I need help on how to provide unique id from the User model to user_id column in profile factory. In my User model I have a relationship with profile:

public function profile()
{
    return $this->hasOne(Profile::class);
}

In profile model:

public function user()
{
    return $this->belongsTo(User::class);
}

And now I have to provide data to profile factory:

 return [
        'user_id' => ,
        'image' => 'image',
        'bio' => $this->faker->sentence,
...
2
  • how about using $this->faker->unique()->randomDigitNotNull;
    – bhucho
    Nov 19, 2020 at 17:30
  • cant use random digit because it may cause an error when 2 users have the same ID :) It is a foreign ID and must be unique. I was wondering if there is way to make profile when the user is made with factory :) Nov 19, 2020 at 19:20

4 Answers 4

2

If you will only create the Profile when you already have a corresponding User, you can leave the user_id out of the Profile factory, and then use the magic methods to create both at the same time.

User::factory()->hasProfiles(1)->create();

This will automatically create a profile to match the user.


Or, if you do need to create a profile before creating a user, you can define the user_id like this in your factory, and a User will be created by the Profile.

return [
    'user_id' => User::factory(),
    'image' => 'image',
    'bio' => $this->faker->sentence,
];
2
  • I like this first way more. So, I just need to call User::factory().... in DatabaseSeeder after calling factory for creating users? Nov 19, 2020 at 19:22
  • Currently, I have these factory calls: prnt.sc/vmeigb Nov 19, 2020 at 19:53
1
'user_id' => $this->faker->unique()->numberBetween(1,5000),
0

The best way is to pass a user_id whenever you need to create a fake profile record.

in profile factory:

return [
        'image' => 'image',
        'bio' => $this->faker->sentence,
...

Wherever you need it:

Profile::factory()->for(User::create() , user)->create();

For more information, you can read this part of the Laravel document.

-1
'user_id' => $this->faker->unique()->numberBetween($min = 1, $max = 500)

Should be total quantity of your users.

1
  • This looks like a duplicate of the answer from Salma mehanny May 16, 2022 at 13:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.