'How to pass arguments to Laravel factories?
I have a users table and a one-to-zero/one relation with a businesses table (users.user_id => businesses.user_id). On my users table I have a discriminator which tells me if the user is of type business and therefore I need to have details on the businesses table as well.
I want to create my Users with my factory which currently is working and then only create business details where the discriminator points to a business account.
I have three options in my mind:
- Create from users factory and then using '->each()' do some checks on the discriminator and create a new business user using a the factory. However I cannot pass to the business factory the
user_idthat the user was assigned. - First create the users. Then in my Business seeder, retrieve all Users that match a 'business' discriminator. Then for all of these users run a factory that creates the business details. But again, I would have to link somehow the
user_idof the already create user with the business factoryuser_id. - In my business factory, create a new User and retrieve the id, thus making the link between
users.user_idandbusiness.user_id. However I am using a random generator foruser.user_typeso even if I have thebusinessestable filled it might be for users that have the discriminator as 'personal'.
Is there another way? Can I pass arguments from my Seeder to the factory?
Solution 1:[1]
My code for adding polymorphic 'Admin' users was:
// run model factory
factory(App\Admin::class, 3)->create()->each(function ($admin) {
$admin->user()->save(
// solved: https://laravel.com/docs/master/database-testing#using-factories (Overriding attributes)
factory(App\User::class)->make([
'userable_id' => $admin->id,
'userable_type' => App\Admin::class
])
);
});
Hope this helps.
Solution 2:[2]
Send attribute,
factory(App\User::class)->create(['businessId' => $businessId]);
Retrieve it,
$factory->define(App\User::class, function (Faker $faker, $businessInfo) {
//$businessInfo['businessId']
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Robin Hood |
| Solution 2 |
