Home

HasMedia

HasMedia is a trait in the Spatie Laravel Media Library package that enables an Eloquent model to own and manage media files. When applied to a model, HasMedia establishes a polymorphic relationship with a Media model, allowing media items to be attached in one or more named collections. These collections organize media independently of the model’s other attributes and can be configured to hold a single item or multiple items.

Architecture and storage:

Media records are stored in a dedicated media table with fields such as model_type, model_id, collection_name,

Key features:

- Attaching media via fluent methods, for example addMedia(...) toMediaCollection('images')

- Support for multiple collections per model and optional single-collection behavior

- Image and file conversions defined in registerMediaConversions

- Retrieval of media and URLs using methods like getMedia, getFirstMediaUrl, or getFirstMedia

- Management of collections through clearMediaCollection and deleteMedia

- Support for responsive images, custom properties, and storage disks (local, S3, etc.)

- Integration with Laravel’s storage system and query capabilities

Usage overview:

- Include the trait in an Eloquent model and, optionally, implement any required interfaces

- Use toMediaCollection to attach files, and getMedia or getFirstMediaUrl to read them

- Define conversions in registerMediaConversions to automatically generate thumbnails or derived formats

See also:

- Spatie Laravel Media Library

- Eloquent relationships

- Laravel storage

file_name,
mime_type,
disk,
and
conversions.
The
HasMedia
trait
provides
the
methods
needed
to
upload,
attach,
retrieve,
and
remove
media,
and
to
configure
how
media
should
be
processed.