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.
This is what worked for me:
App\Models\Client::factory(10)->create()->each(function ($client) {
$client->contract()->save(Contract::factory()->make());
});