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);
}
No comments or questions yet...