In Laravel, handling enums can be done in a few different ways depending on your use case. You can create enums as part of your PHP code (native PHP enums in PHP 8.1+) or use Laravel’s Enum packages like spatie/laravel-enum. Here’s an overview of different ways to handle enums in Laravel:
In PHP 8.1 and above, you can use native enums. Laravel supports these; you can use them within your models, database queries, and validation.
namespace App\Enums;
enum UserType: string {
case ADMIN = 'admin';
case EMPLOYEE = 'employee';
}
use App\Enums\UserType;
class User extends Model
{
protected $casts = [
'type' => UserType::class,
];
}
@if($user->type === UserType::ADMIN)
This user is an admin.
@endif
use App\Enums\UserType;
$validated = $request->validate([
'type' => ['required', Rule::in(UserType::cases())],
]);
You can easily convert enums to strings in JSON responses.
public function toArray() {
return [
'type' => $this->type->value,
];
}
namespace App\Enums;
class UserType {
const ADMIN = 'admin';
const EMPLOYEE = 'employee';
public static function values() {
return [
self::ADMIN,
self::EMPLOYEE,
];
}
}
You can easily convert enums to strings in JSON responses.
$validated = $request->validate([
'type' => [ 'required', Rule::in(UserType::values())],
]);
In Models: Manually casting using custom mutators or accessors is necessary.
If you need extra functionality like enum validation or database storage in Laravel, you can use a package like spatie/laravel-enum.
composer require spatie/enum
namespace App\Enums;
use Spatie\Enum\Enum;
class UserType extends Enum {}
$validated = $request->validate([
'type' => ['required', Rule::enum(UserType::class)],
]);
Spatie’s package provides additional utilities for handling enums like advanced validation, transforming enums, etc.
When working with enums in the database, you can use a VARCHAR or ENUM column type in your migrations.
Schema::table('users', function (Blueprint $table) {
$table->enum('type', ['admin', 'employee']);
});
Combine it with native PHP enums or a custom casting class.
protected $casts = [ 'type' => UserType::class, ];
Type Safety: If you’re using PHP 8.1+, prefer native enums for type safety and simplicity.
Database Compatibility: Use a VARCHAR column in your database instead of an ENUM column if you anticipate the possibility of adding new enum values in the future.
Validation: Always validate enum values to ensure valid data is being processed.
Work with our skilled Laravel developers to accelerate your project and boost its performance.
Hire Laravel Developer