Introduction

Your can have media attached to your models through media collections.

Defining collections

Let's say you have a Blog model that can needs to have a single featured image and a number if carousel images that you'll allow the user to upload. There are two ways of defined media collections for your models.

Your own models

Use the HasMedia trait on your model and add a mediaCollections method. In this method you will define and return an array of the media collections for your Blog model.

1<?php
2 
3namespace App\Models;
4 
5use Helix\Lego\Media\HasMedia;
6use Helix\Lego\Media\Mediable;
7use Helix\Lego\Media\MediaCollection;
8use Helix\Lego\Models\Model;
9 
10class Blog extends Model
11{
12 use HasMedia;
13 
14 public function mediaCollections() : array
15 {
16 return [
17 MediaCollection::name('Featured')->maxFiles(1),
18 MediaCollection::name('Carousel'),
19 ];
20 }
21 
22 // ...
23}

Third party models

Some Strata apps allows its models to have media as well, but since you can't modify the source code to add the mediaCollections() method we have to define it a different way. The HasMedia trait exposes a static setMediaCollections method that we can call from anywhere.

1Astrogoat\Shop\Product::setMediaCollections([
2 MediaCollection::name('Featured')->maxFiles(1),
3 MediaCollection::name('Carousel'),
4]);

Tip: A good place to put this is in the public static function init() method in your Site::class if you want your sites to have different media collections or in the boot method in your AppServiceProvider if you want them to be global.

Accessing media

To access the uploaded media we can make use of some of the methods provided by the trait we added to the Blog model.

1@foreach($blog->getMediaFromCollection('carousel') as $mediaItem) {
2 {!! $mediaItem !!}
3@endforeach

The getMediaFromCollection method returns an instance of MediaCollection just like the Media brick does. So you can use this just like you interact with media from a section brick.

Inteacting with media collections from the admin

You'll most likely also need to let the user upload media and attach it to you model in the backend somewhere. Strata provides a component that you can include in your Blade files.

1<x-lego::media-panel :model="$blog" />

Just passed it the Mediable model you're working with. This component will not persist and media automatically unless you use it in conjuntion with a Helix\Lego\Http\Livewire\Models\Form component. If you're not using the Form to interact with your model than you can persist the media with $blog->push() instead of $blog->save(), see the Laravel documentation for more about the push() method.