Defining media collections | laravel-medialibrary | Spatie

 SPATIE

  Laravel Media Library
========================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-medialibrary](https://spatie.be/docs/laravel-medialibrary/v9)  Working-with-media-collections  Defining media collections

 Version   v11   v10   v9   v8   v7   v6   v5   v4   v3

 Other versions for crawler [v11](https://spatie.be/docs/laravel-medialibrary/v11) [v10](https://spatie.be/docs/laravel-medialibrary/v10) [v9](https://spatie.be/docs/laravel-medialibrary/v9) [v8](https://spatie.be/docs/laravel-medialibrary/v8) [v7](https://spatie.be/docs/laravel-medialibrary/v7) [v6](https://spatie.be/docs/laravel-medialibrary/v6) [v5](https://spatie.be/docs/laravel-medialibrary/v5) [v4](https://spatie.be/docs/laravel-medialibrary/v4) [v3](https://spatie.be/docs/laravel-medialibrary/v3)

- [ Introduction ](https://spatie.be/docs/laravel-medialibrary/v9/introduction)
- [ Support us ](https://spatie.be/docs/laravel-medialibrary/v9/support-us)
- [ Base installation ](https://spatie.be/docs/laravel-medialibrary/v9/installation-setup)
- [ Questions and issues ](https://spatie.be/docs/laravel-medialibrary/v9/questions-issues)
- [ Requirements ](https://spatie.be/docs/laravel-medialibrary/v9/requirements)
- [ Upgrading ](https://spatie.be/docs/laravel-medialibrary/v9/upgrading)
- [ Changelog ](https://spatie.be/docs/laravel-medialibrary/v9/changelog)
- [ Troubleshooting ](https://spatie.be/docs/laravel-medialibrary/v9/troubleshooting)
- [ About us ](https://spatie.be/docs/laravel-medialibrary/v9/about-us)

Basic usage
-----------

- [ Preparing your model ](https://spatie.be/docs/laravel-medialibrary/v9/basic-usage/preparing-your-model)
- [ Associating files ](https://spatie.be/docs/laravel-medialibrary/v9/basic-usage/associating-files)
- [ Retrieving media ](https://spatie.be/docs/laravel-medialibrary/v9/basic-usage/retrieving-media)

Working with media collections
------------------------------

- [ Simple media collections ](https://spatie.be/docs/laravel-medialibrary/v9/working-with-media-collections/simple-media-collections)
- [ Defining media collections ](https://spatie.be/docs/laravel-medialibrary/v9/working-with-media-collections/defining-media-collections)

Converting images
-----------------

- [ Defining conversions ](https://spatie.be/docs/laravel-medialibrary/v9/converting-images/defining-conversions)
- [ Retrieving converted images ](https://spatie.be/docs/laravel-medialibrary/v9/converting-images/retrieving-converted-images)
- [ Optimizing converted images ](https://spatie.be/docs/laravel-medialibrary/v9/converting-images/optimizing-converted-images)
- [ Regenerating images ](https://spatie.be/docs/laravel-medialibrary/v9/converting-images/regenerating-images)

Handling uploads with Media Library Pro
---------------------------------------

- [ Introduction ](https://spatie.be/docs/laravel-medialibrary/v9/handling-uploads-with-media-library-pro/introduction)
- [ Installation ](https://spatie.be/docs/laravel-medialibrary/v9/handling-uploads-with-media-library-pro/installation)
- [ Processing uploads on the server ](https://spatie.be/docs/laravel-medialibrary/v9/handling-uploads-with-media-library-pro/processing-uploads-on-the-server)
- [ Handling uploads with Blade ](https://spatie.be/docs/laravel-medialibrary/v9/handling-uploads-with-media-library-pro/handling-uploads-with-blade)
- [ Handling uploads with Livewire ](https://spatie.be/docs/laravel-medialibrary/v9/handling-uploads-with-media-library-pro/handling-uploads-with-livewire)
- [ Handling uploads with Vue ](https://spatie.be/docs/laravel-medialibrary/v9/handling-uploads-with-media-library-pro/handling-uploads-with-vue)
- [ Handling uploads with React ](https://spatie.be/docs/laravel-medialibrary/v9/handling-uploads-with-media-library-pro/handling-uploads-with-react)
- [ Creating custom Vue components ](https://spatie.be/docs/laravel-medialibrary/v9/handling-uploads-with-media-library-pro/creating-custom-vue-components)
- [ Creating custom React components ](https://spatie.be/docs/laravel-medialibrary/v9/handling-uploads-with-media-library-pro/creating-custom-react-components)
- [ Customizing CSS ](https://spatie.be/docs/laravel-medialibrary/v9/handling-uploads-with-media-library-pro/customizing-css)

Responsive images
-----------------

- [ Getting started with responsive images ](https://spatie.be/docs/laravel-medialibrary/v9/responsive-images/getting-started-with-responsive-images)
- [ Using your own width calculator ](https://spatie.be/docs/laravel-medialibrary/v9/responsive-images/using-your-own-width-calculator)
- [ Customizing the rendered html ](https://spatie.be/docs/laravel-medialibrary/v9/responsive-images/customizing-the-rendered-html)
- [ Generating your own tiny placeholder ](https://spatie.be/docs/laravel-medialibrary/v9/responsive-images/generating-your-own-tiny-placeholder)
- [ Responsive images demo ](https://spatie.be/docs/laravel-medialibrary/v9/responsive-images/demo)

Converting other file types
---------------------------

- [ Using image generators ](https://spatie.be/docs/laravel-medialibrary/v9/converting-other-file-types/using-image-generators)
- [ Creating a custom image generator ](https://spatie.be/docs/laravel-medialibrary/v9/converting-other-file-types/creating-a-custom-image-generator)

Downloading media
-----------------

- [ Downloading a single file ](https://spatie.be/docs/laravel-medialibrary/v9/downloading-media/downloading-a-single-file)
- [ Downloading multiple files ](https://spatie.be/docs/laravel-medialibrary/v9/downloading-media/downloading-multiple-files)

Advanced usage
--------------

- [ Working with multiple filesystems ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/working-with-multiple-filesystems)
- [ Using custom properties ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/using-custom-properties)
- [ Storing media specific manipulations ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/storing-media-specific-manipulations)
- [ Using your own model ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/using-your-own-model)
- [ Outputting media ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/outputting-media)
- [ Rendering media ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/rendering-media)
- [ Using a custom directory structure ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/using-a-custom-directory-structure)
- [ Ordering media ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/ordering-media)
- [ Using a custom media downloader ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/using-a-custom-media-downloader)
- [ Moving media ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/moving-media)
- [ Consuming events ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/consuming-events)
- [ Generating custom urls ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/generating-custom-urls)
- [ Overriding default filesystem behavior ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/overriding-the-default-filesystem-behaviour)
- [ Naming generated files ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/naming-files)
- [ Disable CDN ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/disable-cdn)
- [ Customising Database Connections ](https://spatie.be/docs/laravel-medialibrary/v9/advanced-usage/customising-database-connections)

API
---

- [ Adding files ](https://spatie.be/docs/laravel-medialibrary/v9/api/adding-files)
- [ Defining conversions ](https://spatie.be/docs/laravel-medialibrary/v9/api/defining-conversions)

      You are viewing the documentation for **an older version** of this package. You can check the version you are using with the following command:

 `                                    composer show spatie/laravel-medialibrary                                                                                                                                                                                                                                    `

Defining media collections
==========================

###  On this page

1. [ Are you a visual learner? ](#content-are-you-a-visual-learner)
2. [ Getting registered media collections ](#content-getting-registered-media-collections)
3. [ Defining a fallback URL or path ](#content-defining-a-fallback-url-or-path)
4. [ Only allow certain files in a collection ](#content-only-allow-certain-files-in-a-collection)
5. [ Only allow certain mimetypes in a collection ](#content-only-allow-certain-mimetypes-in-a-collection)
6. [ Using a specific disk ](#content-using-a-specific-disk)
7. [ Single file collections ](#content-single-file-collections)
8. [ Limited file collections ](#content-limited-file-collections)
9. [ Registering media conversions ](#content-registering-media-conversions)
10. [ Generating responsive images ](#content-generating-responsive-images)

A media collection can be more than [just a name to group files](/laravel-medialibrary/v9/working-with-media-collections/simple-media-collections). By defining a media collection in your model you can add certain behaviour collections.

To get started with media collections add a function called `registerMediaCollections` to [your prepared model](/laravel-medialibrary/v9/basic-usage/preparing-your-model). Inside that function you can use `addMediaCollection` to start a media collection.

```
// in your model

public function registerMediaCollections(): void
{
    $this->addMediaCollection('my-collection')
        //add options
        ...

    // you can define as many collections as needed
    $this->addMediaCollection('my-other-collection')
        //add options
        ...
}
```

Are you a visual learner?
---------------------------------------------------------------------------------------------------------------------------------

Here's a video that shows how to work with media collections.

Want to see more videos like this? Check out our [free video course on how to use Laravel Media Library](https://spatie.be/videos/discovering-laravel-media-library).

Getting registered media collections
--------------------------------------------------------------------------------------------------------------------------------------------------------------------

To retrieve all registered media collections on your model you can use the `getRegisteredMediaCollections` method.

```
$mediaCollections = $yourModel->getRegisteredMediaCollections();
```

This returns a collection of `MediaCollection` objects.

Defining a fallback URL or path
-----------------------------------------------------------------------------------------------------------------------------------------------------

If your media collection does not contain any items, calling `getFirstMediaUrl` or `getFirstMediaPath` will return `null`. You can change this by setting a fallback url and/or path using `useFallbackUrl` and `useFallbackPath`.

```
use Spatie\MediaLibrary\MediaCollections\File;
...
public function registerMediaCollections(): void
{
    $this
        ->addMediaCollection('avatars')
        ->useFallbackUrl('/images/anonymous-user.jpg')
        ->useFallbackPath(public_path('/images/anonymous-user.jpg'));
}
```

Only allow certain files in a collection
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

You can pass a callback to `acceptsFile` that will check if a file is allowed into the collection. In this example we only accept `jpeg` files.

```
use Spatie\MediaLibrary\MediaCollections\File;
...
public function registerMediaCollections(): void
{
    $this
        ->addMediaCollection('only-jpegs-please')
        ->acceptsFile(function (File $file) {
            return $file->mimeType === 'image/jpeg';
        });
}
```

This will succeed:

```
$yourModel->addMedia('beautiful.jpg')->toMediaCollection('only-jpegs-please');
```

This will throw a `Spatie\MediaLibrary\Exceptions\FileCannotBeAdded\FileUnacceptableForCollection` exception:

```
$yourModel->addMedia('ugly.ppt')->toMediaCollection('only-jpegs-please');
```

Only allow certain mimetypes in a collection
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

You can defined an array of accepted Mime types using `acceptsMimeTypes` that will check if a file with a certain Mime type is allowed into the collection. In this example we only accept `image/jpeg` files.

```
use Spatie\MediaLibrary\MediaCollections\File;

// ...

public function registerMediaCollections(): void
{
    $this
        ->addMediaCollection('only-jpegs-please')
        ->acceptsMimeTypes(['image/jpeg']);
}
```

This will succeed:

```
$yourModel->addMedia('beautiful.jpg')->toMediaCollection('only-jpegs-please');
```

This will throw a `Spatie\MediaLibrary\Exceptions\FileCannotBeAdded\FileUnacceptableForCollection` exception:

```
$yourModel->addMedia('ugly.ppt')->toMediaCollection('only-jpegs-please');
```

Using a specific disk
-----------------------------------------------------------------------------------------------------------------------

You can ensure that files added to a collection are automatically added to a certain disk.

```
// in your model

public function registerMediaCollections(): void
{
    $this
       ->addMediaCollection('big-files')
       ->useDisk('s3');
}
```

When adding a file to `big-files` it will be stored on the `s3` disk.

```
$yourModel->addMedia($pathToFile)->toMediaCollection('big-files');
```

You can still specify the disk name manually when adding media. In this example the file will be stored on `alternative-disk` instead of `s3`.

```
$yourModel->addMedia($pathToFile)->toMediaCollection('big-files', 'alternative-disk');
```

Single file collections
-----------------------------------------------------------------------------------------------------------------------------

If you want a collection to hold only one file you can use `singleFile` on the collection. A good use case for this would be an avatar collection on a `User` model. In most cases you'd want to have a user to only have one `avatar`.

```
// in your model

public function registerMediaCollections(): void
{
    $this
        ->addMediaCollection('avatar')
        ->singleFile();
}
```

The first time you add a file to the collection it will be stored as usual.

```
$yourModel->addMedia($pathToImage)->toMediaCollection('avatar');
$yourModel->getMedia('avatar')->count(); // returns 1
$yourModel->getFirstMediaUrl('avatar'); // will return an url to the `$pathToImage` file
```

When adding another file to a single file collection the first one will be deleted.

```
// this will remove other files in the collection
$yourModel->addMedia($anotherPathToImage)->toMediaCollection('avatar');
$yourModel->getMedia('avatar')->count(); // returns 1
$yourModel->getFirstMediaUrl('avatar'); // will return an url to the `$anotherPathToImage` file
```

This video shows you a demo of a single file collection.

Limited file collections
--------------------------------------------------------------------------------------------------------------------------------

Whenever you want to limit the amount of files inside a collection you can use the `onlyKeepLatest(n)` method. Whenever you add a file to a collection and exceed the given limit, MediaLibrary will delete the oldest file(s) and keep the collection size at `n`.

```
// in your model

public function registerMediaCollections(): void
{
    $this
        ->addMediaCollection('limited-collection')
        ->onlyKeepLatest(3);
}
```

For the first 3 files, nothing strange happens. The files get added to the collection and the collection now holds all 3 files. Whenever you decide to add a 4th file, MediaLibrary deletes the first file and keeps the latest 3.

```
$yourModel->addMedia($firstFile)->toMediaCollection('limited-collection');
$yourModel->getMedia('avatar')->count(); // returns 1
$yourModel->addMedia($secondFile)->toMediaCollection('limited-collection');
$yourModel->getMedia('avatar')->count(); // returns 2
$yourModel->addMedia($thirdFile)->toMediaCollection('limited-collection');
$yourModel->getMedia('avatar')->count(); // returns 3
$yourModel->addMedia($fourthFile)->toMediaCollection('limited-collection');
$yourModel->getMedia('avatar')->count(); // returns 3
$yourModel->getFirstMediaUrl('avatar'); // will return an url to the `$secondFile` file
```

Registering media conversions
-----------------------------------------------------------------------------------------------------------------------------------------------

It's recommended that your first read the section on [converting images](/laravel-medialibrary/v9/converting-images/defining-conversions) before reading the following paragraphs.

Normally image conversions are registered inside the `registerMediaConversions` function on your model. However, images conversions can also be registered inside media collections.

```
use Spatie\MediaLibrary\MediaCollections\Models\Media;

// ...

public function registerMediaCollections(): void
{
    $this
        ->addMediaCollection('my-collection')
        ->registerMediaConversions(function (Media $media) {
            $this
                ->addMediaConversion('thumb')
                ->width(100)
                ->height(100);
        });
}
```

When adding an image to `my-collection` a thumbnail that fits inside 100x100 will be created.

```
$yourModel->addMedia($pathToImage)->toMediaCollection('my-collection');

$yourModel->getFirstMediaUrl('my-collection', 'thumb') // returns an url to a 100x100 version of the added image.
```

Take a look at the [defining conversions section](/laravel-medialibrary/v9/converting-images/defining-conversions) to learn all the functions you can tack on to `addMediaConversion`.

Generating responsive images
--------------------------------------------------------------------------------------------------------------------------------------------

If you want to also generate responsive images for any media added to a collection you defined, you can simply use `withResponsiveImages` while defining it.

```
// in your model

public function registerMediaCollections(): void
{
    $this
        ->addMediaCollection('my-collection')
        ->withResponsiveImages();
}
```
