Skip to content

Instantly share code, notes, and snippets.

@domthomas-dev
Last active February 28, 2024 11:01
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save domthomas-dev/78e1db6da82512b716b0f8cac6dd93e7 to your computer and use it in GitHub Desktop.
Save domthomas-dev/78e1db6da82512b716b0f8cac6dd93e7 to your computer and use it in GitHub Desktop.
<?php
//Enums/ContactType.php
namespace App\Enums;
use App\Enums\Traits\LocalizedEnum;
enum ContactType: string
{
use LocalizedEnum;
case Manager = 'manager';
case Managing = 'managing';
case Billing = 'billing';
}
<?php
//lang/en/enums.php
use App\Enums\ContactType;
return [
ContactType::class => [
ContactType::Manager->name => 'Manager Label',
ContactType::Managing->name => 'Managing Label',
ContactType::Billing->name => 'Billing Label',
'description' => [
ContactType::Manager->name => 'description for manager case',
ContactType::Managing->name => 'description for managing case',
ContactType::Billing->name => 'description for billing case',
],
],
];
<?php
//Enums/Traits/LocalizedEnum.php
namespace App\Enums\Traits;
use Illuminate\Support\Facades\Lang;
trait LocalizedEnum
{
public function label(?string $specificLabel = null, array $replace=[], ?string $locale = null): ?string
{
$localizationKey = $this->getLocalizationKey($specificLabel);
if (Lang::has($localizationKey, $locale)) {
return __($localizationKey, $replace, $locale);
}
return null;
}
public function getLocalizationKey(?string $specificLabel = null): string
{
return collect([
'enums',
$this::class,
$specificLabel,
$this->name,
])->filter()
->join('.')
;
}
public static function forSelect(?string $specificLabel = null, array $replace=[], ?string $locale = null): array
{
return array_combine(
array_column(self::cases(), 'value'),
array_map(
fn($c) => $c->label($specificLabel, $replace, $locale) ?? $c->name,
self::cases(),
),
);
}
}
{{ $contact->type->label() }}
{{ $contact->type->label('description') }}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment