Using Enum on Laravel routes: A practical guide

Updated: January 15, 2024 By: Guest Contributor Post a comment

Introduction

With the evolution of programming language features and the growth of web applications, it’s always important to write clear and maintainable code. Leveraging enums with Laravel routes can improve the readability and reliability of your application by providing a set of predefined constants that represent a finite set of possible values. In this guide, we’ll explore how to use enums in Laravel routes—starting from basic use cases to more advanced examples.

Prerequisites: To follow along with this tutorial, you should have a basic understanding of PHP and Laravel, as well as have Laravel installed on your system.

Step-by-Step Instructions

Step 1: Define Your Enum

use BenSampo\Enum\Enum;

final class UserRole extends Enum
{
    const Administrator = 'administrator';
    const Editor = 'editor';
    const Subscriber = 'subscriber';
}

Before diving into routes, we first need to define an enum. Laravel, as of version 8.x, does not support native enum types in PHP; however, you can use the third-party package BenSampo/laravel-enum to create enums. Install it using composer require bensampo/laravel-enum.

Step 2: Configure Route Parameter Constraint

Route::get('/user/{role}', function (UserRole $role) {
    // Your route logic here
});

In Laravel, we can type-hint the enum in a route parameter to automatically cast the incoming parameter to our enum type. If the parameter does not match an enum value, Laravel throws a 404 NotFoundException.

Step 3: Using Enum in Route Logic

Route::get('/user/{role}', function (UserRole $role) {
    return view('user.index', ['users' => User::where('role', $role->value)->get()]);
});

Here we’re injecting the UserRole enum directly into our route and using its value to filter users by their role.

Step 4: Middleware Integration

Route::get('/admin/dashboard', function () {
    // Admin dashboard logic here
})->middleware(['can:isAdmin', 'can:viewDashboard']);

This example demonstrates how to protect routes with middleware. We’re not directly using enums here, but it’s a setup for our next step.

Step 5: Middleware with Enums

public function handle($request, Closure $next, UserRole $role)
{
    if(auth()->user()->role !== $role->value) {
        abort(403);
    }
    return $next($request);
}

We’ve just created a middleware that uses our UserRole enum to check if the authenticated user has the correct role before proceeding with the request.

Step 6: Route Caching with Enums

Caching routes can significantly improve the performance of your application. However, caching dynamic values like those coming from enums can be tricky. A common approach is to resolve dynamic values before allowing Laravel to cache the routes.

Enumerating Routes

foreach (UserRole::getValues() as $role) {
    Route::get('/user/'. $role, '\…')->name('user.' . $role);
}

That’s a pattern to dynamically create routes using enum values as part of the route definition itself.

Conclusion

Throughout this tutorial, we’ve seen how enums, when used in Laravel routes, can lead to more descriptive and safer routing mechanisms. By following these examples, you can better express your intentions and business logic directly in your Laravel application’s routing layer.