Vincent Decaux
Vincent Decaux

Reputation: 10714

Laravel Factory Can't Save Relation

I use Laravel 5.6, and I have a problem with my seeder.

I use this :

factory(\App\Models\Merchant::class)->create([
    'email' => '[email protected]',
])->each(function ($m) {
    $m->stores()->save(factory(\App\Models\Store::class)->create()
        ->each(function ($s) {
            $s->products()->save(factory(\App\Models\Product::class, 10)->create());
        })
    );
});

All are hasMany relations.

Doing this, I have this error :

General error: 1364 Field 'merchant_id' doesn't have a default value (SQL: insert into stores ....)

It's like my first $stores->save( ... ) doesn't use the merchant created.

In my DB, I have one merchant created.

If I use ->make() instead of ->create(), it works for the Store, but I can't save products because it's not persisted...

Is it possible to use multiple save in factories like this ?

Upvotes: 0

Views: 842

Answers (1)

thisiskelvin
thisiskelvin

Reputation: 4202

Your code may need a little refactoring as you may be chaining creation of models incorrectly:

factory(\App\Models\Merchant::class, 2)->create([
    'email' => '[email protected]',
])->each(function ($m) {
    $store = factory(\App\Models\Store::class)->create(['merchent_id' => $m->id]);
    factory(\App\Models\Product::class, 10)->create(['store_id' -> $store->id]);
    );
});

Note: In order to use the ->each() method, you need to have a collection instance. I do not think creating only one merchant will return a collection. In the example, we create 2 merchents.

Upvotes: 2

Related Questions