Home

toMediaCollection

toMediaCollection is a method in the Spatie Laravel Media Library package. It attaches a media item to a named collection on a model, completing the upload process that began with addMedia or addMediaFromUrl. The method helps organize files by logical groups, such as images, documents, or avatars, by placing them into distinct collections on the same model.

The typical signature is toMediaCollection(string $collectionName = 'default', string|null $diskName = null). The first parameter specifies the collection

Usage examples:

- $user->addMedia($request->file('avatar'))->toMediaCollection('avatars');

- $post->addMediaFromUrl('https://example.com/file.pdf')->toMediaCollection('documents', 'public');

Retrieval and management of media items are done via the model’s media collections, for example getMedia('avatars')

Notes:

- toMediaCollection is part of the broader Media Library workflow, which includes adding media, manipulating properties, and

- The operation respects the configured disks and can raise validation or filesystem errors if the file

See also:

- Spatie Laravel Media Library

- HasMedia trait

- getMedia and getMediaCollection methods

- addMedia and addMediaFromUrl methods

name,
with
a
default
value
of
'default'
if
none
is
provided.
The
optional
second
parameter
allows
selecting
a
specific
storage
disk.
When
invoked,
the
library
creates
a
Media
record
associated
with
the
model,
stores
the
file
on
the
chosen
disk,
and
assigns
the
media
item
to
the
specified
collection.
or
getFirstMedia('documents').
The
method
is
commonly
used
in
conjunction
with
the
HasMedia
trait,
which
provides
the
necessary
interface
for
managing
media
on
Eloquent
models.
retrieving
items.
cannot
be
stored.