Closed markinigor closed 5 years ago
Not sure I understand this. Could you elaborate as the changes don't line up with the PR comments. What are you suggesting the closure does that the inline reference does not?
Without this request relations factories allway wil create model, even if we override the attribute
$factory->define(App\User::class, function (Faker\Generator $faker) {
return [
'company_id' => factory(App\Company::class)->create()->id, //Always creates model, even we override attribute
];
});
factory(App\User::class)->create([
'company_id' => factory(App\Company::class)->create()->id
])
echo App\Company::count(); // Will return 2, but we expect 1
With this PR:
$factory->define(App\User::class, function (Faker\Generator $faker) {
return [
'company_id' => factory(App\Company::class), //Creates model and return its id only when the attribute does not exists in factory params.
];
});
factory(App\User::class)->create([
'company_id' => factory(App\Company::class)->create()->id
])
echo App\Company::count(); // Will return 1
Interesting. Thanks for the explanation, I see now what you are trying to prevent. I am going to review the docs and core as this is interesting behavior.
Both of the examples you provided return 2
for me. This is actually more of a PHP lazy-execution thing, than a Laravel thing.
I am going to close this and open a new PR to wrap the relationships in a closure as they are outlined in the docs that way.
Hm, It's weird. Any way Closure will be great too. P.s. This tip for a factory I see in Laracasts https://laracasts.com/series/build-a-laravel-app-with-tdd/episodes/14 at 14:01
Nice. Going to close this and submit a fresh patch. Thanks for all the feedback.
It allows to override value without creating another model instance. It works like a closure