Description
Laravel Rest Api Version
2.8.7
Laravel Version
11.30
PHP Version
8.3
Database Driver & Version
No response
Description
I am encountering an issue with the implementation of polymorphic relations (MorphTo) in the library. Following the documentation's guidelines, I configured my model and resource as instructed, but the implementation fails with a 500 Internal Server Error.
Observed Behavior
The API fails with the following error:
Call to a member function resource() on null
Upon debugging with Laravel Telescope, I traced the error to this line:
$relationResource = $relationConcrete->resource();
It seems the $relationConcrete object is null when resolving the physicalPeople or moralPeople relations.
Expected Behavior
The MorphTo relations (physicalPeople and moralPeople) should resolve correctly and return the associated Resource class (PhysicalPeopleResource or MoralPeopleResource), depending on the personable_type in the model.
Additional Context
If necessary, I can provide further debugging logs or a minimal reproducible example. Please let me know how to proceed or if additional information is required.
Thank you for your help! 😊
As a note in the first versions of the library when it was allowed to declare the polymorphic relationship with an array of Resources it was perfectly functional.
Steps To Reproduce
- Configure the model as shown in the documentation:
public function personable(): MorphTo
{
return $this->morphTo();
}
public function physicalPeople(): MorphTo
{
return $this->personable()->whereHas('people', function (Builder $query) {
$query->where('people.personable_type', 'physical');
});
}
public function moralPeople(): MorphTo
{
return $this->personable()->whereHas('people', function (Builder $query) {
$query->where('people.personable_type', 'moral');
});
}
- Add the relations to the Resource class:
public function relations(RestRequest $request): array
{
return [
HasOne::make('referrer', ReferrerResource::class),
HasMany::make('addresses', AddressResource::class),
HasMany::make('documents', DocumentResource::class),
HasMany::make('emails', EmailResource::class),
HasMany::make('phones', PhoneResource::class),
HasMany::make('clients', ClientResource::class),
MorphTo::make('physicalPeople', PhysicalPeopleResource::class),
MorphTo::make('moralPeople', MoralPeopleResource::class),
HasOne::make('legalClassification', LegalClassificationResource::class),
HasOne::make('promoter', PromoterResource::class),
HasOne::make('referer', RefererResource::class),
HasOne::make('rfc', DocumentResource::class),
BelongsTo::make('type', TypeResource::class),
];
}
3.Make an API request that tries to resolve one of the MorphTo relations.