This packages makes it easy to add and manage media associated with models.
Require the package through Composer
$ composer require spatie/laravel-medialibrary
Register the service provider and the MediaLibrary facade.
// config/app.php
'providers' => [
...
'Spatie\MediaLibrary\MediaLibraryServiceProvider',
];
// config/app.php
'aliases' => [
...
'MediaLibrary' => 'Spatie\MediaLibrary\MediaLibraryFacade',
];
Next publish the configuration
$ php artisan vendor:publish --provider="Spatie\MediaLibrary\MediaLibraryServiceProvider"
You can separately publish the config or the migration using the config
or migrations
tag.
Next run the migration for the Media table
$ php artisan migrate
The publicPath
key in the configuration is where the generated images are stored. This is set to a sensible default already.
The globalImageProfiles
is a way to set global image profiles. (These can be overwritten by a models image profiles).
Models have to use the MediaLibraryModelTrait to gain access to the needed methods.
All examples assume $user = User::find(1);
Return all media from a certain collection belonging to a $user.
$user->getMedia('images');
getMedia has an optionals $filters argument.
Returns only the first media-record from a certain collection belonging to a $user.
$user->getFirstMedia('images');
Returns the URL of the first media-item with given collectionName and profile
$user->getFirstMediaURL('images', 'small');
Add a media-record using a file and a collectionName.
$user->addMedia('testImage.jpg', 'images');
addMedia has optional $preserveOriginal and $addAsTemporary arguments.
Remove a media-record ( and associated generated files) by its id
$user->removeMedia(1);
Update the media-records with given information ( and automatically reorder them).
$user->updateMedia([
['id' => 1, 'name' => 'updatedName'],
], 'images');
You can also opt to use the MediaLibrary-facade directly (which the trait uses).
MediaLibrary::add($file, MediaLibraryModelInterface $model, $collectionName, $preserveOriginal = false, $addAsTemporary = false);
The same as addMedia but the model is an argument.
MediaLibrary::remove($id);
The same as removeMedia but without a bit of validation.
MediaLibrary::order($orderArray, MediaLibraryModelInterface $model);
Reorders media-records (order_column) for a given model by the $orderArray.
$orderArray should look like [1 => 4, 2 => 3, ... ]
where the key is the media-records id and the value is what value order_column should get.
MediaLibrary::getCollection(MediaLibraryModelInterface $model, $collectionName, $filters);
Same as getMedia without the default $filters set to 'temp' => 1
MediaLibrary::cleanUp();
Deletes all temporary media-records and associated files older than a day.
MediaLibrary::regenerateDerivedFiles($media);
Removes all derived files for a media-record and regenerates them.
We have a User-model. A user must be able to have pdf files associated with them.
Firstly, make use of the MediaLibraryModelTrait in your model.
class User extends Model {
use MediaLibraryModelTrait;
...
}
Next you can add the files to the user like this:
$user->addMedia($pathToFile, 'pdfs');
Remove it like this:
$user->removeMedia($id);
//$id is the media-records id.
This will also delete the file so use with care.
Update it like this:
$updatedMedia = [
['id' => 1, 'name' => 'newName'],
];
$user->updateMedia($updatedMedia, 'pdfs');
Get media-records like this:
$media = $user->getMedia('pdfs');
Now you can loop over these to get the url's to the files.
foreach($media as $profileName => $mediaItem)
{
$fileURL = $mediaItem->getAllProfileURLs();
}
// $fileURL will be ['original' => '/path/to/file.pdf]
Let's say we have a User-model that needs to have images associated with it.
After installing the package (migration, config, facade, service provider) we add the MediaLibraryModelTrait to our User model.
This gives you access to all needed methods.
class User extends Model {
use MediaLibraryModelTrait;
...
}
If you use this package for images ( like this example) the model should have the public $imageProfiles member.
Example:
public $imageProfiles = [
'small' => ['w' => '150', 'h' => '150', 'filt' => 'greyscale', 'shouldBeQueued' => false],
'medium' => ['w' => '450', 'h' => '450'],
'large' => ['w' => '750', 'h' => '750' , 'shouldBeQueued' => true],
];
The shouldBeQueued-key is optional and will default to true if absent.
The MediaLibrary utilizes Glide so take a look at Glide's image api.
Say our user uploads an image to the application that needs to have the versions specified in the User-model.
Firstly 'get' the user.
$user = User::find(1);
Then, use the trait to 'add the media'.
$pathToUploadedImage = storage_path('uploadedImage.jpg');
$user->addMedia($pathToUploadedImage, 'images');
This will generate all images specified in getImageProfileProperties and insert a record into the Media-table. The images will be placed in the path set in the publicPath in the config.
Say we want to update some media records.
We need to give an array containing an array for each record that needs to be updated.
$updatedMedia = [
['id' => 1, 'name' => 'newName'],
['id' => 2, 'collection_name' => 'newCollectionName'],
];
$user->updateMedia($updatedMedia, 'images');
If the given collectionName doesn't check out an exception will be thrown. Media-record with id 1 will have its name updated and media-records with id 2 will have its collection_name updated.
$user->removeMedia(1);
Remove a media-record and its associated files with removeMedia() and the id of the media-records as a parameter.
Displaying media by passing 'media' to a view:
// In controller
$user = User::find(1);
$media = $user->getMedia('images');
return view('a_view')
->with(compact('media');
In your view, this would display all media from the images collection for a certain $user
@foreach($media as $mediaItem)
@foreach($mediaItem->getAllProfileURLs() as $profileName => $imageURL)
<img src="{{ url($imageURL) }}">
@endforeach
@endforeach
Please see CONTRIBUTING for details.
If you discover any security related issues, please email [email protected] instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.