Skip to content

HasMany relation and media library inside the relation #531

@Skiexx

Description

@Skiexx

When trying to create a HasMany link using Resolver and custom Layout, there is a problem inside the object.

Using trait HasMediaLibrary there is a problem that the library considers the parent model as containing HasMedia interface. The problem is with HasMediaLibrary and the method getUnderlyingMediaModel, which returns not the child model, but the parent model as the owner of HasMedia. As a result it returns the error 'Origin HasMedia model not found.'

Code:

class ChildrenLayout extends Layout implements HasMedia
{
    use HasMediaLibrary;
    ...
    public function fields()
    {
        return [
            ID::make()->sortable(),

            Text::make(__('Title'), 'title')
                ->rules('required', 'max:50')
                ->filterable()
                ->sortable(),

            Textarea::make(__('Text'), 'text')
                ->rules('required', 'max:250')
                ->hideFromIndex(),

            Images::make(__('Image'), 'image')
                ->required()
                ->rules('required')
                ->singleImageRules('required'),
        ];
    }
}


class ChildrenResolver implements ResolverInterface
{
    public function get($resource, $attribute, $layouts)
    {
        $childrens = $resource->children()->orderBy('order')->get();
        $layout = $layouts->find('children');

        return $childrens->map(function (Children $children) use ($layout) {
            return $layout->duplicateAndHydrate(
                $children->id,
                [
                    'id' => $children->id,
                    'title' => $children->title,
                    'text' => $children->text,
                    'order' => $children->order,
                    'image' => $children->getMedia('image')
                ]);
        })->filter()->values();
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions