Laravel Nova MorphOne - set default fields based on relation
I am using the MorphMany and MorphOne relationship types to define addresses and a primary address for multiple models, a given model can have many addresses, but only one primary address.
I also require that when a model is created that has addresses, the primary address be created at the same time, which means I use the MorphOne field and make it required on the resource.
This works just fine. However, on my Address model, I have the property: is_primary. What I need to do is set is_primary to be true by default IF the address being created is the primary address, and set to false otherwise. But when using Nova, if I check to see if the Address is being created viaRelationship, I get the underlying morphMany relationship of addresses not primaryAddress.
So, how do I get the Address resource to recognize if the creation form is being displayed in the context of the MorphOne field instead of just a normal creation field?
Example resource that has addresses:
public function fields(NovaRequest $request): array
{
return [
Text::make('First Name'),
Text::make('Last Name'),
BelongsTo::make('Type', 'type', TrainerType::class),
MorphOne::make('Primary Address', 'primaryAddress', Address::class)
->required()
->onlyOnForms(),
MorphMany::make('Addresses', 'addresses', Address::class)
->onlyOnDetail(),
];
}
Address resource:
public function fields(NovaRequest $request): array
{
return [
Text::make('Address Line 1'),
$this->getIsPrimaryField($request),
];
}
protected function getIsPrimaryField(NovaRequest $request)
{
//$request->viaRelationship only ever shows 'addresses', not 'primaryAddress'
if ($request->viaRelationship === 'primaryAddress') {
return Boolean::make('Is Primary')
->default(true)
->readonly()
->withMeta([
'extraAttributes' => ['readonly' => true],
'value' => true
]);
}
return Boolean::make('Is Primary')->default(false);
}
Please or to participate in this conversation.