Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here
Tutorial Free

Resize Images in Laravel with Spatie Media Library

April 17, 2019
2 min read

Really popular Laravel Media Library package has one less-known feature - image resizing. The best part is that it's really simple to add, let me show you how.

If you prefer video version, here it is below:


And now - text version of the tutorial.

If you need to save resized image version while uploading the file, like generate a thumbnail for the photo, all you need to do is add this method registerMediaConversions() to your Model:

use Illuminate\Database\Eloquent\Model;
use Spatie\MediaLibrary\Models\Media;
use Spatie\MediaLibrary\HasMedia\HasMedia;
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;

class NewsItem extends Model implements HasMedia
{
    use HasMediaTrait;

    public function registerMediaConversions(Media $media = null)
    {
        $this->addMediaConversion('thumb')
              ->width(150)
              ->height(100);
    }
}

Also, don't forget to add use Spatie\MediaLibrary\Models\Media; to the top.

This method will generate a resized thumbnail with maximum 150px width and maximum 100px height (resized proportionally) and put it in storage/app/public/[media_id]/conversions folder:

In database media table, it will be saved with custom_properties of registered media name(s).

And then you will be able to access that specific conversion by the same name you used here:

So, if your Media Collection name is named cover, you can view the thumbnail image like this:

<img src="{{ $book->getFirstMediaUrl('cover', 'thumb') }}" />

You can also register multiple conversions for the same model, just add more rules to the method:

public function registerMediaConversions(Media $media = null)
{
    $this->addMediaConversion('thumb')
        ->width(150)
        ->height(100);
    $this->addMediaConversion('bigthumb')
        ->width(300)
        ->height(100);
}

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.