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
- $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')
- 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
- Spatie Laravel Media Library