How to seed related data during migration in Laravel?

276 Views Asked by At

I have a table clients and a table contracts. In my Client model I have

public function contract()
    {
        return $this->hasOne(
            'App\Models\Contract',
            'client_id',
            'id'
        );
    }

I don't want to have any client without a contract in my database. When I seed my clients, using the factory with faker data, I want to create contracts that are mapped to client using the foreign key user_id on the contract.

2

There are 2 best solutions below

0
On BEST ANSWER

This is what worked for me:

App\Models\Client::factory(10)->create()->each(function ($client) {
    $client->contract()->save(Contract::factory()->make());
});
0
On

make sure to make a factory for each table and then you can simply do something like

        Client::factory()
        ->count(3)
        ->has(Contract::factory()->forUser()->create())
        ->create();

Notice: check your relations in your models then it should be fine :)