Laravel-medialibrary: [Question] How to get responsive srcSet media urls (for api json response)?

Created on 9 Nov 2018  路  1Comment  路  Source: spatie/laravel-medialibrary

How to get media srcset for include in my json response? Ex.:

`
public function getImagesUrlAttribute()
{
return [
'thumb' => $this->getFirstMediaUrl('image', 'thumb'),
'small' => $this->getFirstMediaUrl('image', 'small'),
'medium' => $this->getFirstMediaUrl('image', 'medium'),
'high' => $this->getFirstMediaUrl('image', 'high'),
'responsive' => $this->getFirstMediaUrlSrcSet('image', 'responsive')
];
}

...

public function registerMediaCollections()
{

    $this->addMediaCollection('image')
            ->singleFile()
            ->useDisk('s3')
            ->acceptsFile(function (File $file) {
                return $file->mimeType === 'image/jpeg';
            })
            ->registerMediaConversions(function (Media $media) {

                $this->addMediaConversion('thumb')
                        ->crop(Manipulations::CROP_CENTER, 160, 160)
                        ->sharpen(8);

                $this->addMediaConversion('small')
                        ->crop(Manipulations::CROP_CENTER, 320, 320)
                        ->sharpen(8);

                $this->addMediaConversion('medium')
                        ->crop(Manipulations::CROP_CENTER, 720, 720)
                        ->sharpen(10);

                $this->addMediaConversion('high')
                        ->crop(Manipulations::CROP_CENTER, 1080, 1080)
                        ->sharpen(10);

                $this->addMediaConversion('responsive')
                        ->withResponsiveImages();
            });
}

`

Most helpful comment

I think you'll just get an image url if you do it like this.
$this->getFirstMediaUrl('images', 'high'),

but you could fetch the image instance before hand:
$image = collect($this->getMedia('images'))->first();

and then perform a $image->getSrcset('high') and $image->getUrl('high') on it.

>All comments

I think you'll just get an image url if you do it like this.
$this->getFirstMediaUrl('images', 'high'),

but you could fetch the image instance before hand:
$image = collect($this->getMedia('images'))->first();

and then perform a $image->getSrcset('high') and $image->getUrl('high') on it.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

netanelwebninja picture netanelwebninja  路  3Comments

Krato picture Krato  路  4Comments

eichgi picture eichgi  路  3Comments

intrepidws picture intrepidws  路  3Comments

xron89 picture xron89  路  3Comments