isap-ou / laravel-enum-helpers
Helpers for native PHP enums in Laravel: translatable labels, value collections for migrations, MySQL enum column sync, and export to JavaScript.
Requires
- illuminate/contracts: ^9|^10|^11|^12|^13
Requires (Dev)
None
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Helpers for native PHP enums in Laravel:
- Translatable labels for enum cases, compatible with FilamentPHP.
- Value collections for migrations and validation:
ExampleEnum::values(),ExampleEnum::keys(). - MySQL enum column sync: one Artisan command updates
ENUMcolumns when you add or remove a case. - Export to JavaScript: one Artisan command generates frozen JS objects from your enums.
Installation
You can install the package via composer:
composer require isap-ou/laravel-enum-helpers
You will most likely need to edit the extensive configuration, so you can publish the config file with:
php artisan vendor:publish --tag="enum-helpers-config"
Default config
return [ 'enum_locations' => [ 'app/Enums' => '\\App\\Enums\\', ], 'label' => [ 'prefix' => 'enums', 'namespace' => null, ], 'post_migrate' => true, 'js_objects_file' => 'resources/js/enums.js', ];
enum_locations- path where enums located. Key is directory with enums, value - namespace for specified directorypost_migrate- enable or disable post migrate event listenerjs_objects_file- path for generated js outputlabel.prefix- get default prefix for translations of enum fields (defaultenums, so labels are read fromlang/{locale}/enums.php)label.namespace- get default prefix for translations of enum namespace (when using as part of own package)
Laravel Boost
This package ships an agent skill for Laravel Boost. The skill teaches your AI agent how to use the helpers below.
Boost offers the skill when isap-ou/laravel-enum-helpers is a direct dependency in your application's composer.json.
Run the installer and select the package:
php artisan boost:install
If Boost is already installed, run the update command instead:
php artisan boost:update
Available helpers
Migration helper
The way easy to add all enums to database column.
Just add to Enum trait InteractWithCollection
use IsapOu\EnumHelpers\Concerns\InteractWithCollection; enum ExampleEnum: string { use InteractWithCollection; case ENUM_ONE = 'enum_one'; case ENUM_TWO = 'enum_two'; }
And in migration class
use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('table_name', function (Blueprint $table){ ... $table->enum('enum_column', ExampleEnum::values()->toArray()); ... }); } }
Update enum columns in DB
Artisan command allows update available(possible) values for specific enum column.
Modify enum:
use IsapOu\EnumHelpers\Contracts\UpdatableEnumColumns; enum ExampleEnum: string implements UpdatableEnumColumns { case ENUM_ONE = 'enum_one'; case ENUM_TWO = 'enum_two'; public static function tables(): array { return [ 'table_name' => 'enum_column' ]; } }
Set column defaults (optional)
You can instruct the migrator to set a DEFAULT for specific enum columns.
If an enum class defines a static method tableColumnDefaults(), the command will append DEFAULT <value> to the generated SQL for the matching table_column keys.
/** * Map "table_column" => enum case. * The migrator will generate "... DEFAULT '<case->value>'". * * @return array<string, self> */ public static function tableColumnDefaults(): array { return [ 'orders_status' => self::NEW, 'order_items_status' => self::NEW, ]; }
And run command
php artisan enum-helpers:migrate:enums
There is also a listener enabled by default that will run after a successful migration.
To disable it edit enum-helpers.php:
<?php return [ ... 'post_migrate' => false, ... ]
Convert PHP Enums to JS objects
Artisan command allows generate js objects based on enums
Modify enum:
use IsapOu\EnumHelpers\Contracts\JsConvertibleEnum; enum ExampleEnum: string implements JsConvertibleEnum { case ENUM_ONE = 'enum_one'; case ENUM_TWO = 'enum_two'; }
And run command
php artisan enum-helpers:js:export
Output will
export const ExampleEnum = Object.freeze({ENUM_ONE:"enum_one", ENUM_TWO:"enum_two"});
You can specify output path in config enum-helpers.php
return [ ... 'js_objects_file' => 'resources/js/enums.js' ... ]
Label Helper
The Label helper allows you to transform an enum instance into a textual label, making it useful for displaying human-readable, translatable enum values in your UI.
use IsapOu\EnumHelpers\Concerns\HasLabel; enum ExampleEnum: string { use HasLabel; case ENUM_ONE = 'enum_one'; case ENUM_TWO = 'enum_two'; }
You can retrieve a textual label for an enum case using the getLabel method:
ExampleEnum::ENUM_ONE->getLabel()
By default, the getLabel method attempts to find a translation key, following this format: ExampleEnum.ENUM_ONE.
1. ExampleEnum - The class name of the enum.
2. ENUM_ONE - The enum case name.
Parameters
The getLabel method accepts three optional parameters:
1. prefix: Prepends a prefix to the translation key.
2. namespace: Prepends a namespace to the translation key. This is particularly useful when developing packages.
3. locale: Allows you to specify the locale for translation. If not provided, the app’s default locale will be used.
Example with custom parameters:
ExampleEnum::ENUM_ONE->getLabel('custom_prefix', 'custom_namespace', 'fr');
This will retrieve the French (fr) translation with the specified prefix and namespace.
getLabels Method
The getLabels method returns a collection of labels for all enum cases, making it convenient to retrieve or display translatable labels for multiple enum values at once.
$labels = ExampleEnum::getLabels(); // Output: // Illuminate\Support\Collection {#1234 // all: [ // "ENUM_ONE" => "Enum One Label", // "ENUM_TWO" => "Enum Two Label", // ], // }
Customizing Prefix, Namespace, and Locale
You can customize the prefix, namespace, and locale for the translations when retrieving labels for all cases:
$customLabels = ExampleEnum::getLabels('custom_prefix', 'custom_namespace', 'fr');
Global Configuration for Prefix and Namespace
You can define the prefix and namespace globally in the configuration file enum-helpers.config,
or override them on the enum level by defining the following methods:
protected function getPrefix(): ?string { return 'prefix'; } protected function getNamespace(): ?string { return 'namespace'; }
The global or per-enum configurations will be used unless you provide custom values when calling getLabel or getLabels.
Optional. Interface
\IsapOu\EnumHelpers\Contracts\HasLabelfor better IDE support
For better IDE support, you can implement the \IsapOu\EnumHelpers\Contracts\HasLabel interface. This helps provide autocomplete suggestions and improves code hinting for the getLabel method when working with enums.
FilamentPHP Compatibility
This helper is fully compatible with Enums in FilamentPHP
use Filament\Support\Contracts\HasLabel; use IsapOu\EnumHelpers\Concerns\HasLabel as HasLabelTrait; enum ExampleEnum: string implements HasLabel { use HasLabelTrait; case ENUM_ONE = 'enum_one'; case ENUM_TWO = 'enum_two'; }
Contributing
Please, submit bugs or feature requests via the Github issues.
Pull requests are welcomed!
Thanks!
License
This project is open-sourced software licensed under the MIT License.
You are free to use, modify, and distribute it in your projects, as long as you comply with the terms of the license.
Maintained by ISAPP and ISAP OÜ.
Check out our software development services at isap.me.
