How to add image props array in resouce?

81 views Asked by At

In laravel 9 I want to join $CMSItem object and properties of related image(I use spatie/laravel-medialibrary) in one resource, having in control :

$CMSItem = CMSItem
    ::getById($cms_item_id)
    ->with('author')
    ->first();


$CMSItemImage = [];
foreach ($CMSItem->getMedia(config('app.media_app_name')) as $mediaImage) {
    if (File::exists($mediaImage->getPath())) {
        $CMSItemImage['url']       = $mediaImage->getUrl();
        $imageInstance = Image::load($mediaImage->getUrl());
        $CMSItemImage['width']     = $imageInstance->getWidth();
        $CMSItemImage['height']    = $imageInstance->getHeight();
        $CMSItemImage['size']      = $mediaImage->size;
        $CMSItemImage['file_title'] = $mediaImage->file_title;
        break;
    }
}

and in file app/Http/Resources/CMSItemResource.php:

class CMSItemResource extends JsonResource
{
    public function toArray($request)
    {
        $dateFunctionality = App::make(DateFunctionality::class);

        return [
            'id'              => $this->id,
            'title'           => $this->title,
            'key'             => $this->key,
            'text'            => $this->text,
            'author_id'       => $this->author_id,
            'author'          => new UserResource($this->whenLoaded('author')),
            'media_image_url' => $this->media_image_url,

            'published'            => $this->published,
            'published_formatted'  => $dateFunctionality->getFormattedDateTime($this->published),
            'created_at'           => $this->created_at,
            'created_at_formatted' => $dateFunctionality->getFormattedDateTime($this->created_at),
            'updated_at'           => $this->updated_at,
            'updated_at_formatted' => $dateFunctionality->getFormattedDateTime($this->updated_at),
        ];
    }

    public function with($request)
    {
        return [
            'meta' => [
                'version' => getAppVersion()
            ]
        ];
    }

}

I do not see in which way can i pass image props array in resouce ?

Thanks!

1

There are 1 answers

0
mstdmstd On BEST ANSWER

I found decision with defining attributes in model:

protected $attributes= ['mediaImageProps'];
public function setMediaImagePropsAttribute(array $mediaImageProps)
{
    $this->attributes['mediaImageProps'] = $mediaImageProps;
}

public function getMediaImagePropsAttribute(): array
{
    return $this->attributes['mediaImageProps'] ?? []; 
}

and assigning in control :

$CMSItem->mediaImageProps= $CMSItemImage;