Skip to content

Instantly share code, notes, and snippets.

@stevebauman
Created May 28, 2024 17:07
Show Gist options
  • Save stevebauman/4ae4f41606a82c818ecd921b793500ef to your computer and use it in GitHub Desktop.
Save stevebauman/4ae4f41606a82c818ecd921b793500ef to your computer and use it in GitHub Desktop.
Enum Based Laravel Media Collection Registration
<?php
namespace App\Models;
// ...
use App\Enums\UserMediaCollection;
class User extends Authenticatable
{
// ...
public function registerMediaCollections(): void
{
UserMediaCollection::Avatar->register($this);
UserMediaCollection::Music->register($this);
}
}
<?php
namespace App\Enums;
use App\Models\User;
enum UserMediaCollection: string
{
case Avatar = 'avatar';
case Music = 'music';
public function register(User $user): void
{
$user->addMediaCollection($this->value)
->acceptsFile(function (File $file) {
return $file->size <= $this->size()
&& in_array($file->mimeType, $this->mimes());
});
}
public function size(): int
{
return match ($this) {
case self::Avatar => 2 * pow(1024, 2) // 2 MB
case self::Music => 10 * pow(1024, 2), // 10 MB
};
}
public function mimes(): array
{
return match ($this) {
case self::Avatar => [
'image/jpeg',
'image/png',
'image/gif',
],
case self::Music => [
'audio/wav',
'audio/mpeg',
'audio/flac',
'audio/x-wav',
'audio/x-m4a',
],
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment