Skip to content

Helpers for handling enums in Laravel

License

Notifications You must be signed in to change notification settings

jesperbjerke/laravel-enums

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Laravel Enums

This package provides a trait with helper methods for enum management and translation in Laravel.

Important: This package has been rebuilt as of v2 to work with native PHP enums instead of class constants. As such, PHP 8.1 is now required. See UPGRADE.md for more details.

Requirements:

Installation:

composer require bjerke/laravel-enums

Usage:

namespace App\Enums;

use Bjerke\Enum\HasTranslations;
use Bjerke\Enum\UsesTranslations;

enum PostStatus: int implements HasTranslations {
    use UsesTranslations;

    case DRAFT = 10;
    case PUBLISHED = 20;
    case ARCHIVED = 30;
}

Which will then allow you to define the translated versions of these values in Laravel translation file called enums.php:

// ../resources/lang/en/enum.php

use App\Enums\MyEnum;

return [
    'post_status' => [
        PostStatus::DRAFT->value => 'Draft',
        PostStatus::PUBLISHED->value => 'Published'
        PostStatus::ARCHIVED->value => 'Archived'
    ]
];

Which in turn will enable you to fetch the translated values as:

PostStatus::DRAFT->translate(); // return translation for this case
PostStatus::getTranslations(); // return all translations

There's also a helper method for retrieving cases:

PostStatus::getCasesAsArray() - Returns an array of "enum key" => "enum value"