Installation Add the package via Composer:
composer require commerceguys/enum
No additional configuration is required—it’s a standalone library.
First Use Case: Define an Enum
Create a basic enum class (e.g., UserRole.php):
use CommerceGuys\Enum\AbstractEnum;
class UserRole extends AbstractEnum
{
const ADMIN = 'admin';
const EDITOR = 'editor';
const VIEWER = 'viewer';
protected static $values = [
self::ADMIN,
self::EDITOR,
self::VIEWER,
];
}
Use it in your code:
$role = UserRole::from('admin'); // Returns UserRole instance
echo $role->getValue(); // Outputs: 'admin'
Key Methods to Explore First
from($value): Convert a string/value to an enum instance.isValid($value): Check if a value is valid for the enum.getValues(): Get all allowed values as an array.getValue(): Get the raw value of the enum instance.Validation Replace manual string checks with enum validation:
if (UserRole::isValid($request->input('role'))) {
$role = UserRole::from($request->input('role'));
}
Database Integration Use enums for Eloquent model attributes:
class User extends Model
{
protected $casts = [
'role' => UserRole::class, // Automatically casts to UserRole enum
];
}
Laravel’s casts will handle serialization/deserialization.
API Responses Return enum values in JSON responses:
return response()->json([
'role' => $user->role->getValue(), // 'admin', 'editor', etc.
]);
Switch Statements Replace magic strings with type-safe enums:
switch ($user->role->getValue()) {
case UserRole::ADMIN:
// Handle admin logic
break;
case UserRole::EDITOR:
// Handle editor logic
break;
}
$this->app->singleton(UserRole::class, function () {
return UserRole::from('default');
});
public function rules()
{
return [
'role' => ['required', Rule::in(UserRole::getValues())],
];
}
@if($user->role === UserRole::ADMIN)
<button>Admin Actions</button>
@endif
Case Sensitivity
Enum values are case-sensitive by default. Use strtolower() or strtoupper() if needed:
UserRole::from(strtolower($input)); // Force lowercase
Duplicate Values
Ensure self::$values contains unique values—duplicates will cause issues during validation.
Serialization Quirks Enums may not serialize/deserialize cleanly in some contexts (e.g., Redis). Cast to raw values explicitly:
$serialized = $user->role->getValue(); // Store this instead of the enum
AbstractEnum Inheritance
Extend AbstractEnum directly. Avoid intermediate abstract classes unless necessary.
isValid() before from() to avoid exceptions:
if (!UserRole::isValid($value)) {
throw new \InvalidArgumentException("Invalid role: {$value}");
}
getValue() or isValid() if custom logic is needed (e.g., for legacy systems).Custom Validation
Extend AbstractEnum to add validation rules:
class UserRole extends AbstractEnum
{
protected static function validateValue($value)
{
if (strlen($value) > 10) {
throw new \InvalidArgumentException("Role too long");
}
return parent::validateValue($value);
}
}
Dynamic Enums Load values from a database or config:
class DynamicRole extends AbstractEnum
{
protected static $values;
public static function loadFromConfig()
{
self::$values = config('roles.available');
}
}
DynamicRole::loadFromConfig();
Backward Compatibility
For PHP < 5.6, use getValues() instead of [] syntax:
$values = UserRole::getValues(); // Array of strings
Performance Cache enum instances if instantiated frequently:
static $instances = [];
public static function from($value)
{
if (!isset(self::$instances[$value])) {
self::$instances[$value] = parent::from($value);
}
return self::$instances[$value];
}
How can I help you explore Laravel packages today?