To retrieve files you can use the getMedia
-method:
$mediaItems = $newsItem->getMedia();
The method returns a collection of Media
-objects.
You can retrieve the url and path to the file associated with the Media
-object using getUrl
, getTemporaryUrl
(for S3 only) and getPath
:
$publicUrl = $mediaItems[0]->getUrl();
$fullPathOnDisk = $mediaItems[0]->getPath();
$temporaryS3Url = $mediaItems[0]->getTemporaryUrl(Carbon::now()->addMinutes(5));
Since retrieving the first media and the url for the first media for an object is such a common scenario, the getFirstMedia
and getFirstMediaUrl
convenience-methods are also provided:
$media = $newsItem->getFirstMedia();
$url = $newsItem->getFirstMediaUrl();
An instance of Media
also has a name, by default its filename:
echo $mediaItems[0]->name;
$mediaItems[0]->name = 'new name';
$mediaItems[0]->save();
The name of a Media
instance can be changed when it's added to the medialibrary:
$newsItem
->addMedia($pathToFile)
->usingName('new name')
->toMediaCollection();
The name of the uploaded file can be changed via the media-object:
$mediaItems[0]->file_name = 'newFileName.jpg';
$mediaItems[0]->save();
The name of the uploaded file can also be changed when it gets added to the media-library:
$newsItem
->addMedia($pathToFile)
->usingFileName('otherFileName.txt')
->toMediaCollection();
You can sanitize the filename using a callable:
$newsItem
->addMedia($pathToFile)
->sanitizingFileName(function($fileName) {
return strtolower(str_replace(['#', '/', '\\', ' '], '-', $fileName));
})
->toMediaCollection();
You can also retrieve the size of the file via size
and human_readable_size
:
$mediaItems[0]->size;
$mediaItems[0]->human_readable_size;
An instance of Media
also contains the mime type of the file.
$mediaItems[0]->mime_type;
You can remove something from the library by simply calling delete
on an instance of Media
:
$mediaItems[0]->delete();
When a Media
instance gets deleted all related files will be removed from the filesystem.
Deleting a model with associated media, will also delete all associated files.
$newsItem->delete();
If you want to remove all associated media in a specific collection you can use the clearMediaCollection
method. It also accepts the collection name as an optional parameter:
$newsItem->clearMediaCollection();
$newsItem->clearMediaCollection('images');
Also, there is a clearMediaCollectionExcept
method which can be useful if you want to remove only few or some selected media in a collection. It accepts the collection name as the first argument and the media instance or collection of media instances which should not be removed as the second argument:
$newsItem->clearMediaCollectionExcept('images', $newsItem->getFirstMedia());