Not a month has gone by since v2 of the laravel-medialibrary package got released. If you’re not familiar with it: the package provides an easy way to associate files with Eloquent models. Though I was quite happy with the improvements made over v1 there were some things that bothered me.
Take a look at the signature of the addMedia function:
public function addMedia($file, $collectionName = 'default', $removeOriginal = true, $addAsTemporary = false)
It accepts two booleans. It’s perfectly understandable what the booleans do when looking at the function signature. When using the function it becomes less clear:
$model->addMedia('test.jpg', 'images', false, true);
Using booleans as parameters wasn’t a good idea. I couldn’t improve this function without making breaking changes. That’s why the version number had to be bumped up from v2 to v3.
In the shiny new version of the medialibrary the addMedia-function is replaced with a fluent interface:
The new way of adding a files is a lot more readable. As a bonus new functions can be added to this fluent interface without making breaking changes.
Another new feature is that the package can now handle uploads directly. Previously only a file could be added. You had to do this to add a file to the medialibrary:
$file = $request->get('file');
$targetDirectory = storage_path('temp');
$targetFileName = $file->getClientOriginalName());
$media = $yourModel->addMedia($targetDirectory.'/'.$targetFileName, $collectionName);
The equivalent code using v3 of the medialibrary is:
Besides the new way of adding files the package can now use multiple filesystems to store media. When adding a file to the medialibrary you can choose on which disk the file should be stored:
This is useful when for example you have some small files that should be stored locally and some big files that you want to save on s3.
Another neat addition is that custom properties can be stored on a media object:
->withCustomProperties(['mime-type' => 'image/jpeg'])
If you’re coming from a previous version and want to upgrade to the latest release check out the upgrade instructions to learn how to upgrade. If you’re new to the package you can read the entire installation and usage guide on GitHub: