Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to retrieve converted image in Spatie laravel-medialibrary?

I’m uploading images using the spatie media library and the images get uploaded and converted successfully. When accessing an uploaded image as below it works:

 @foreach ($articles as $article)
     <h1>{{ $article->title }}</h1>
     <img src="{{ $article->getFirstMediaUrl() }}" alt="">
 @endforeach 

How can I access the converted images? I think I’m missing something from the documentation to make it work.

My model

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;



class Article extends Model implements HasMedia
{
    use HasFactory, InteractsWithMedia;

    protected $fillable = ['title'];

    public function registerMediaConversions(Media $media = null): void
    {
        $this->addMediaConversion('thumb')
            ->width(250)
            ->height(90);
    }
}

My store function

  public function store(Request $request)
    {
        $file = $request->file('image');
        $article = Article::create(['title' => 'First title']);
        $article->addMedia($file)->toMediaCollection();
        return back();
    }

>Solution :

you should use getUrl() method to access the media url, so change your template like this.

<img src="{{ $article->getFirstMediaUrl()->getUrl() }}" alt="">

you will get the converted file perhaps if you want to access other object you can use other library function though from the document
https://spatie.be/docs/laravel-medialibrary/v10/introduction

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading