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:
[code lang="php"] public function addMedia($file, $collectionName = 'default', $removeOriginal = true, $addAsTemporary = false) [/code]
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:
[code lang="php"] $model->addMedia('test.jpg', 'images', false, true); [/code]
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:
[code lang="php"] $model->addMedia('test.jpg') ->preservingOriginal() ->toCollection('images'); [/code]
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:
[code lang="php"] $file = $request->get('file');
$targetDirectory = storage_path('temp'); $targetFileName = $file->getClientOriginalName());
$media = $yourModel->addMedia($targetDirectory.'/'.$targetFileName, $collectionName); [/code]
The equivalent code using v3 of the medialibrary is:
[code lang="php"] $yourModel ->addMedia($request->get('file')) ->toCollection('downloads'); [/code]
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:
[code lang="php"] $model->addMedia('test.jpg') ->toCollectionOnDisk('images', 's3'); [/code]
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:
[code lang="php"] $model->addMedia('test.jpg') ->withCustomProperties(['mime-type' => 'image/jpeg']) ->toCollectionOnDisk('images', 's3'); [/code]
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: https://github.com/spatie/laravel-medialibrary