You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
As its polymorphic nature, I can't know in advance what resource type it will be.
classAddressResourceextendsJsonApiResource
{
public$attributes = [
'label',
'geo_point',
];
public$relationships = [
'owner' => UserResource::class, // But also can be TeamResource, RestaurantResource, etc
];
}
Is there a way to check loaded $resource->owner->getTable() to guest the corresponding type?
Or maybe a trait included in my model with the method getJsonApiResouce(): $this->resource->owner->getJsonApiResource()
I "solved" it by using this in my AppServiceProvider:
JsonApiResource::guessRelationshipResourceUsing(function (string$relationship, JsonApiResource$jsonApiResource) {
if (!$jsonApiResource->resource instanceof EloquentModel) {
returnnull;
}
// TODO: Parametrizar estos namespaces.$modelsNamespace = 'App\\Models\\';
$resourcesNamespace = 'App\\Http\\Resources\\JsonApi\\';
// How can I detect the underlying model class of an Eloquent relationship? Is this OK?$relatedModelClass = get_class($jsonApiResource->resource->{$relationship}()->getModel());
// This will work only for Models following that structure.$relatedResourceClass = str_replace($modelsNamespace, $resourcesNamespace, $relatedModelClass) . 'Resource';
if (!class_exists($relatedResourceClass)) {
thrownew \BadMethodCallException(
"Resource class `{$relatedResourceClass}` not found for relationship `{$relationship}`."
);
}
return$relatedResourceClass;
});
With this resources' resolver, it will guest the resource class by relationship model's class instead of relationship name. But I'm not sure if is it consequent enough for all kind of relationships.
As its polymorphic nature, I can't know in advance what resource type it will be.
Is there a way to check loaded
$resource->owner->getTable()
to guest the corresponding type?Or maybe a trait included in my model with the method
getJsonApiResouce()
:$this->resource->owner->getJsonApiResource()
Or a similar way of doing it, as
User::factory()
works.The text was updated successfully, but these errors were encountered: