Resize image in laravel with spatie media library

Working with images can be easily done using Laravel. But if you use Laravel Spatie Media Library then you can easily bind images to multiple models and perform image manipulation functions like image conversion.

If there is a requirement to convert and save resized image version while uploading the file, like generating a thumbnail for the photo. You can easily do it by using registerMediaConversions() in your model.

The registerMediaConversions() method will convert images into various conversions as per your requirement and store them as a copy. You can simply access those images by calling them with a conversion name.

Let's take an example to implement a single conversion into the User model. Here, we have already installed the Spatie Media Library package otherwise you need to set up it using Composer.

Open the User model and modify it as below:

>?php
namespace App\Models;

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

class User extends Model implements HasMedia
{
    use HasMediaTrait;

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

Here, we have implemented the HasMedia interface into our model and also used HasMediaTrait. Into registerMediaConversions() method we have created image conversion with 150*100 size by thumb name. This conversion name is required while retrieving resized images in further code.

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

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

    $this->addMediaConversion('large_thumb')
          ->width(300)
          ->height(200);
}

In the above example, it will create 2 conversions of image with different dimensions.

Now we can access images using media library methods like getFirstMediaUrl(). Let's take an example to retrieve image.

$user = User::find(1);
$imageURL = $user->getFirstMediaUrl('cover', 'thumb');

Above code will get retrieve the image URL based on the user's relationship with the media table. Here, we have passed the conversion name so it will retrieve the image URL for that particular conversion.

Conclusion

In this article, we have used the Spatie media library to resize or convert image into multiple dimension and store and retrieve it. While working on a major application where images play a common role image resizing plays an important role in reducing load time. You can even use the accessor for appending image_url to the user model.