Oh Dear is the all-in-one monitoring tool for your entire website. We monitor uptime, SSL certificates, broken links, scheduled tasks and more. You'll get a notifications for us when something's wrong. All that paired with a developer friendly API and kick-ass documentation. O, and you'll also be able to create a public status page under a minute. Start monitoring using our free trial now.

Laravel medialibrary hits v4

Original – by Freek Van der Herten – 2 minute read

Today we tagged a new major version of laravel-medialibrary. In case you're not familiar with this package here's a quick rundown of what it can do.

The package can associate all sorts of files with Eloquent models. It provides a simple, fluent API to work with. Here's a quick example:

$newsItem = News::find(1);
$newsItem->addMedia($pathToFile)->toCollection('images');

Want to store some large files on another filesystem? No problem:

$newsItem->addMedia($smallFile)->toCollectionOnDisk('downloads', 'local');
$newsItem->addMedia($bigFile)->toCollectionOnDisk('downloads', 's3');

The package can also generate derived images such as thumbnails for images and pdf's. For this to work you have to prepare your model a bit:

use Illuminate\Database\Eloquent\Model;
use Spatie\MediaLibrary\HasMedia\Interfaces\HasMediaConversions;
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;

class NewsItem extends Model implements HasMediaConversions
{
    use HasMediaTrait;

    public function registerMediaConversions()
    {
        $this->addMediaConversion('thumb')
             ->setManipulations(['w' => 368, 'h' => 232])
             ->performOnCollections('images');
    }
}

Once that's out the way you can to this to retrieve a thumbnail.

$newsItem->getMedia('images')->first()->getUrl('thumb');

If you're already using v3 of the package you'll notice that there hasn't changed much. Upgrading should be fairly painless. V4 is not a feature rich major version. The biggest changes are that Glide 1.0.0 is used behind the scenes to create thumbnails, and some internal functions were refactored.

Thanks to a lot of quality contributions from our users this is easily one of our best packages. If you like this one, take a look at the other ones we've previously made.

Share Post LinkedIn

I write about Laravel, PHP, AI and building better software.

Every two weeks, I share practical tips, tutorials, and behind-the-scenes insights from maintaining 300+ open source packages. Join thousands of developers who read along.

No spam. Unsubscribe anytime. You can also follow me on X.

Found something interesting to share?

The community section is a place where developers share links to articles, tutorials and videos. Submit a link and help fellow developers discover great content. As a thank you, you'll receive a coupon for a discount on Spatie products.