Home > other >  How to retrieve converted image in Spatie laravel-medialibrary?
How to retrieve converted image in Spatie laravel-medialibrary?

Time:06-22

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

<?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();
    }

CodePudding user response:

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

  • Related