Summer Sale! All accounts are 50% off this week.

PatrickSingh's avatar

Laravel 8 factory for polymorph relationship

I am trying to create tests and to do so I need to make factories. This is no problem. But one thing I can't get working is creating factories for my polymorph relationship.

Our app has the following:

Party model with this relation

public function partyable(): MorphTo
{
    return $this->morphTo();
}

Then we have a directory called Parties. In this directory we have the main class called PartyDefault. This has a relation back to the Party.

public function party(): MorphOne
{
   return $this->morphOne(Party::class, 'partyable');
}

So the Party model stores the polymorph fields and the PartyDefault stores the party detail fields. In the parties folder we have more files with a class per party those classes extend the PartyDefault class and they contain the fields used per party.

How can I create a factory which fills both tables (parties and party_details) with fake data and keep them related?

0 likes
3 replies
PatrickSingh's avatar

Thanks I got it to work. Only I needed to add a enforceMorphMap as well to get it to work.

Relation::enforceMorphMap([
			'App\Models\Parties\PartyPolicyHolder' => 'App\Models\Parties\PartyPolicyHolder',
			'App\Models\Parties\PartyIntermediary' => 'App\Models\Parties\PartyIntermediary',
]);

Party::factory()->for(
			PartyPolicyHolder::factory(), 'partyable',
)->create(['claim_id' => $claim->id, 'entity_type' => 'policyHolder']);

Party::factory()->for(
			PartyIntermediary::factory(), 'partyable'
)->create(['claim_id' => $claim->id, 'entity_type' => 'intermediary']);
1 like

Please or to participate in this conversation.