Skip to content

Commit

Permalink
Get registered media collections (#1976)
Browse files Browse the repository at this point in the history
* Add `getRegisteredMediaCollections()` and supporting test

* Add explanation/usage to docs
  • Loading branch information
squatto committed Aug 6, 2020
1 parent e205727 commit 091a1c3
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
10 changes: 10 additions & 0 deletions docs/working-with-media-collections/defining-media-collections.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,16 @@ public function registerMediaCollections(): void
}
```

## Getting registered media collections

To retrieve all registered media collections on your model you can use the `getRegisteredMediaCollections` method.

```php
$mediaCollections = $yourModel->getRegisteredMediaCollections();
```

This returns a collection of `MediaCollection` objects.

## Defining a fallback URL or path

If your media collection does not contain any items, calling `getFirstMediaUrl` or `getFirstMediaPath` will return `null`. You can change this by setting a fallback url and/or path using `useFallbackUrl` and `useFallbackPath`.
Expand Down
7 changes: 7 additions & 0 deletions src/InteractsWithMedia.php
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,13 @@ public function getFirstTemporaryUrl(
return $media->getTemporaryUrl($expiration, $conversionName);
}

public function getRegisteredMediaCollections(): Collection
{
$this->registerMediaCollections();

return collect($this->mediaCollections);
}

public function getMediaCollection(string $collectionName = 'default'): ?MediaCollection
{
$this->registerMediaCollections();
Expand Down
13 changes: 13 additions & 0 deletions tests/MediaCollections/MediaCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Spatie\MediaLibrary\Tests\MediaCollections;

use Spatie\MediaLibrary\MediaCollections\MediaCollection;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
use Spatie\MediaLibrary\Tests\TestCase;

Expand Down Expand Up @@ -30,4 +31,16 @@ public function it_can_get_the_sum_of_all_media_item_sizes()

$this->assertEquals($mediaItem->size + $anotherMediaItem->size, $totalSize);
}

/** @test */
public function it_can_get_registered_media_collections()
{
// the 'avatar' media collection is registered in
// \Spatie\MediaLibrary\Tests\TestSupport\TestModels\TestModel->registerMediaCollections()
$collections = $this->testModel->getRegisteredMediaCollections();

$this->assertCount(1, $collections);
$this->assertInstanceOf(MediaCollection::class, $collections->first());
$this->assertEquals('avatar', $collections->first()->name);
}
}

0 comments on commit 091a1c3

Please sign in to comment.