-
-
Save timmaier/0547238a71ff8361d5c7a16d8e0c351d to your computer and use it in GitHub Desktop.
Enum Based Laravel Media Collection Registration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Models; | |
// ... | |
use App\Enums\UserMediaCollection; | |
class User extends Authenticatable | |
{ | |
// ... | |
public function registerMediaCollections(): void | |
{ | |
UserMediaCollection::Avatar->register($this); | |
UserMediaCollection::Music->register($this); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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