Streamline Your Code: Replace Hardcoded Roles with Enums

✨ The Problem

We often see this in Laravel apps:

if ($user->role === 'admin') {
    // do admin stuff
}

Hardcoded role strings are:

  • ❌ Fragile (a typo breaks everything)

  • ❌ Not type-safe

  • ❌ Repeated everywhere

There’s a better way. Since PHP 8.1, we have native support for Enums, and Laravel integrates with them beautifully (Laravel 9+).


✅ The Clean Way: Use an Enum

1. Create an enum for user roles

namespace App\Enums;

enum UserRole: string
{
    case Admin = 'admin';
    case Editor = 'editor';
    case Viewer = 'viewer';
}

2. Update your User model

use App\Enums\UserRole;

protected $casts = [
    'role' => UserRole::class,
];

Now $user->role will be an actual UserRole enum instance.


3. Use it in your policies or services

if ($user->role === UserRole::Admin) {
    // safe, clear, and typed
}

4. Bonus: Validate it in requests

use Illuminate\Validation\Rules\Enum;
use App\Enums\UserRole;

$request->validate([
    'role' => [new Enum(UserRole::class)],
]);

🧠 Why this matters

  • ✅ No magic strings

  • ✅ Autocomplete and static analysis support

  • ✅ Centralized role definitions

  • ✅ Future-proof: easy to add new roles


📌 Summary

Stop sprinkling raw strings in your code for user roles (or any constants). Use enums — they’ve been available since PHP 8.1, and Laravel works with them natively.

Your code will thank you. So will your future self.

0
Subscribe to my newsletter

Read articles from Jean-Marc Strauven directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Jean-Marc Strauven
Jean-Marc Strauven

Jean-Marc (aka Grazulex) is a developer with over 30 years of experience, driven by a passion for learning and exploring new technologies. While PHP is his daily companion, he also enjoys diving into Python, Perl, and even Rust when the mood strikes. Jean-Marc thrives on curiosity, code, and the occasional semicolon. Always eager to evolve, he blends decades of experience with a constant hunger for innovation.