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.
Media records are stored in a dedicated media table with fields such as model_type, model_id, collection_name,
- 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
- 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