How to pass arguments to Laravel factories?
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.
Send attribute,
factory(App\User::class)->create(['businessId' => $businessId]);
Retrieve it,
$factory->define(App\User::class, function (Faker $faker, $businessInfo) {
//$businessInfo['businessId']
});
The attributes you pass to the create
function will be passed into your model definition callback as the second argument.
In your case you don't even need to access those attributes, since they'll automatically be merged in:
$business = factory(App\Business::class)->create();
factory(App\User::class, 5)->create([
'business_id' => $business->id,
]);
Adapt this to your needs.