Skip to content

Instantly share code, notes, and snippets.

@domthomas-dev
Last active September 12, 2025 15:01
Show Gist options
  • Select an option

  • Save domthomas-dev/78e1db6da82512b716b0f8cac6dd93e7 to your computer and use it in GitHub Desktop.

Select an option

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 => [
'label' => [
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
declare(strict_types=1);
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 $localizationKey;
}
public function getLocalizationKey(?string $specificLabel = null): string
{
return collect([
'enums',
$this::class,
$specificLabel ?? 'label',
$this->name,
])->filter()
->join('.')
;
}
public static function forSelect(?string $specificLabel = null, array $replace = [], ?string $locale = null, array $excepted = [], array $only = [], ?string $placeHolder = null): array
{
if ($placeHolder) {
return ['' => $placeHolder] + self::forSelect($specificLabel, $replace, $locale, $excepted, $only);
}
return array_combine(
array_column(self::filterCases(excepted: $excepted, only: $only), 'value'),
array_map(
fn ($c) => $c->label($specificLabel, $replace, $locale),
self::filterCases(excepted: $excepted, only: $only),
),
);
}
public static function filterCases(array $excepted = [], array $only = []): array
{
if (empty($only)) {
return array_filter(self::cases(), fn ($c) => ! in_array($c, $excepted));
}
return array_filter(self::cases(), fn ($c) => in_array($c, $only));
}
public static function values(): array
{
return array_column(self::cases(), 'value');
}
}
{{ $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