timhale2104/enum-tools 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

timhale2104/enum-tools

Composer 安装命令:

composer require timhale2104/enum-tools

包简介

Enum helpers for Laravel

README 文档

README

version 1.4.0

A lightweight Laravel package that simplifies working with native PHP enums: readable labels, localized API responses, select options, and validation rules.

Features

  • Add human-friendly labels to PHP enums
  • Generate value/label pairs for select menus
  • Use enums in API responses with localization
  • Validate request input against enum values
  • Support for Laravel 10, 11, 12, 13
  • Easy-to-integrate EnumController with built-in protection

Installation

Supports Laravel 10, 11, 12, 13

Install via Composer:

composer require timhale2104/enum-tools

Usage

1. Add HasLabel trait to your enum

use EnumTools\Traits\HasLabel;

enum UserStatus: string
{
    use HasLabel;

    case ACTIVE = 'active';
    case INACTIVE = 'inactive';
    case BLOCKED = 'blocked';
}

2. Available Methods

UserStatus::ACTIVE->label(); // "Active"
UserStatus::labels();        // ['Active', 'Inactive', 'Blocked']
UserStatus::values();        // ['active', 'inactive', 'blocked']
UserStatus::casesForSelect();
// [
//   ['label' => 'Active', 'value' => 'active'],
//   ...
// ]
UserStatus::toArray(); // alias for casesForSelect()

3. Optional Localization

Add translation strings to lang/en/enums.php:

return [
    'UserStatus.active' => 'Custom Active',
    'UserStatus.inactive' => 'Custom Inactive',
    'UserStatus.blocked' => 'Custom Blocked',
];

label will automatically use __('enums.UserStatus.active') if it exists

4. Enum Value Validation

Use the custom validation rule to check if a value is part of a specific enum:

use EnumTools\Rules\EnumValueRule;

$request->validate([
    'status' => ['required', new EnumValueRule(UserStatus::class)],
]);

You'll get a default validation message like:

The selected :attribute is invalid.

You can customize it via lang/en/validation.php:

return [
    'enum' => 'I guess the selected :attribute is not valid',
];

5. Enum Cast for Eloquent

Cast enum values to and from database automatically in Eloquent models.

!!! Requires your enum to extend BackedEnum and use the HasLabel trait !!!

Add the cast like this:

use EnumTools\Casts\EnumToolsCast;
use App\Enums\UserStatus;

protected $casts = [
    'status' => EnumToolsCast::for(UserStatus::class),
];

You can now work with enums directly:

$user = User::create(['status' => UserStatus::ACTIVE]);

$user->status instanceof UserStatus; // true
$user->status->label(); // "Active" (or translated)

API Support

This package includes an API-ready controller to expose enums to your frontend as JSON with localization

API Response Example

GET /api/enums/user-status?lang=uk
{
  "success": true,
  "data": [
    { "value": "active", "label": "Активний" },
    { "value": "inactive", "label": "Неактивний" },
    { "value": "blocked", "label": "Заблокований" }
  ]
}

Protecting Enums

Only enums listed in allowed_enums are accessible via API. Publish the config:

php artisan vendor:publish --provider="EnumTools\EnumToolsServiceProvider" --tag=config

In config/enum_tools.php:

return [
    'namespace' => 'App\\Enums',

    'allowed_enums' => [
        'UserStatus',
    ],

    'enable_locale_middleware' => true,
    'supported_locales' => ['en', 'uk', 'ru'],
];

Register API Route

In your routes/api.php:

use EnumTools\Http\Controllers\EnumController;

Route::get('enums/{enum}', EnumController::class);

API Localization

By default, the API will auto-detect the language from:

  • Query string: ?lang=uk
  • Header: X-Locale: uk
  • Header: Accept-Language: uk

To disable auto-localization:

'enable_locale_middleware' => false,

Frontend Usage Example (Axios)

const { data } = await axios.get('/api/enums/user-status?lang=uk');

if (data.success) {
  const options = data.data;
  // [{ value: 'active', label: 'Активний' }, ...]
}

API Integration with EnumCollectionResource

If you're building a frontend (Vue, React, etc.), you may want to expose enum values and labels via API. This package provides a ready-to-use Laravel Resource for that

EnumCollectionResource

Use EnumCollectionResource::from() to convert any enum into a JSON-ready format

Example

use EnumTools\Resources\EnumCollectionResource;

return response()->json([
    'success' => true,
    'status' => 200,
    'data' => EnumCollectionResource::from(UserStatus::class),
]);

Output

[
  { "value": "active", "label": "Active" },
  { "value": "inactive", "label": "Inactive" },
  { "value": "blocked", "label": "Blocked" }
]

Methods

from(string $enumClass): EnumCollectionResource

Static factory method that accepts a native PHP enum class and wraps it in a resource collection

Internally, it's just a shortcut for new EnumCollectionResource(UserStatus::cases())

toArray($request): array

This defines how each enum case will be returned in JSON. By default, it returns:

[
  'label' => $case->label(), // requires HasLabel trait
  'value' => $case->value, // or case name for unit enums
]

If the label() method is missing, it falls back to case->name

When to use

  • You want a frontend-friendly API format
  • You're using enums in select fields, dropdowns, filters
  • You need a Laravel-native approach that supports localization

Artisan Generator: enum-tools:make

You can generate a new enum class preconfigured for Enum Tools:

php artisan enum-tools:make UserStatus

Laravel 13 includes its own make:enum command, so Enum Tools uses a namespaced command to avoid collisions.

This will create a file like app/Enums/UserStatus.php:

use EnumTools\Traits\HasLabel;
use EnumTools\Attributes\Label;
use EnumTools\Attributes\Color;
use EnumTools\Attributes\Icon;

enum UserStatus: string
{
    use HasLabel;

    #[Label('Example')]
    #[Color('green')]
    #[Icon('check-circle')]
    case EXAMPLE = 'example';
}

Example:

UserStatus::EXAMPLE->label(); // "Example"
UserStatus::EXAMPLE->color(); // "green"
UserStatus::EXAMPLE->icon();  // "check-circle"

Available immediately after installing the package

timhale2104/enum-tools 适用场景与选型建议

timhale2104/enum-tools 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 6 次下载、GitHub Stars 达 1, 最近一次更新时间为 2025 年 07 月 08 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「validation」 「enum」 「laravel」 「select」 「label」 「enums」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 timhale2104/enum-tools 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 timhale2104/enum-tools 我们能提供哪些服务?
定制开发 / 二次开发

基于 timhale2104/enum-tools 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 6
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 12
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-07-08