Skip to content

How to define a morphTo relationship? #53

Open
@nelson6e65

Description

@nelson6e65

As its polymorphic nature, I can't know in advance what resource type it will be.

class AddressResource extends JsonApiResource
{
    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()

class User extends Model IHasJsonApiResource
{
    use HasFactory;

    /**
     * @return class-string<JsonApiResource>
     */
    public function getJsonApiResouce(): string
    {
        return UserResource::class;
    }
    
}

Or a similar way of doing it, as User::factory() works.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions