PHPackages                             timhale2104/enum-tools - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. timhale2104/enum-tools

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

timhale2104/enum-tools
======================

Enum helpers for Laravel

v1.4.0(10mo ago)16MITPHPPHP ^8.1

Since Jul 8Pushed 10mo agoCompare

[ Source](https://github.com/VenSnow/laravel-enum-tools)[ Packagist](https://packagist.org/packages/timhale2104/enum-tools)[ RSS](/packages/timhale2104-enum-tools/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (1)Versions (6)Used By (0)

Enum Tools for Laravel
======================

[](#enum-tools-for-laravel)

**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
--------

[](#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
- Easy-to-integrate `EnumController` with built-in protection

Installation
------------

[](#installation)

Supports **Laravel 10, 11, 12**

Install via Composer:

```
composer require timhale2104/enum-tools
```

Usage
-----

[](#usage)

### 1. Add HasLabel trait to your enum

[](#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

[](#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

[](#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

[](#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 status is not valid. `

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

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

---

### 5. Enum Cast for Eloquent

[](#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
-----------

[](#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

[](#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

[](#register-api-route)

In your `routes/api.php`:

```
use EnumTools\Http\Controllers\EnumController;

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

---

### API Localization

[](#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)

[](#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
-------------------------------------------

[](#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

[](#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

[](#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,
]
```

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

### When to use

[](#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: `make:enum`

[](#artisan-generator-makeenum)

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

```
php artisan make:enum UserStatus
```

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('Приклад')]
    #[Color('green')]
    #[Icon('check-circle')]
    case EXAMPLE = 'example';
}
```

**Example:**

```
UserStatus::EXAMPLE->label(); // "Приклад"
UserStatus::EXAMPLE->color(); // "green"
UserStatus::EXAMPLE->icon();  // "check-circle"
```

Available immediately after installing the package

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance54

Moderate activity, may be stable

Popularity6

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~1 days

Total

5

Last Release

311d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/5e71742487425e11b3cceb97186df2c178867fc92896a172f8bb0d0401bb888b?d=identicon)[timhale2104](/maintainers/timhale2104)

---

Top Contributors

[![VenSnow](https://avatars.githubusercontent.com/u/71027251?v=4)](https://github.com/VenSnow "VenSnow (6 commits)")

---

Tags

laravelvalidationenumselectlabelenums

### Embed Badge

![Health badge](/badges/timhale2104-enum-tools/health.svg)

```
[![Health](https://phpackages.com/badges/timhale2104-enum-tools/health.svg)](https://phpackages.com/packages/timhale2104-enum-tools)
```

###  Alternatives

[bensampo/laravel-enum

Simple, extensible and powerful enumeration implementation for Laravel.

2.0k15.9M104](/packages/bensampo-laravel-enum)[propaganistas/laravel-phone

Adds phone number functionality to Laravel based on Google's libphonenumber API.

3.0k35.7M107](/packages/propaganistas-laravel-phone)[proengsoft/laravel-jsvalidation

Validate forms transparently with Javascript reusing your Laravel Validation Rules, Messages, and FormRequest

1.1k2.3M49](/packages/proengsoft-laravel-jsvalidation)[axlon/laravel-postal-code-validation

Worldwide postal code validation for Laravel and Lumen

3853.3M1](/packages/axlon-laravel-postal-code-validation)[wendelladriel/laravel-validated-dto

Data Transfer Objects with validation for Laravel applications

759569.4k13](/packages/wendelladriel-laravel-validated-dto)[laravel-validation-rules/credit-card

Validate credit card number, expiration date, cvc

2412.2M5](/packages/laravel-validation-rules-credit-card)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
