Laravel Tutorials

Enum-Powered Route Permissions in Laravel

Published
Enum-Powered Route Permissions in Laravel image

Laravel has simplified permission checks in routes by adding direct enum support to the can() method. This enhancement eliminates the need to access the enum's value property explicitly, resulting in cleaner and more expressive route definitions.

This feature particularly shines when building admin panels or multi-tenant applications where permission management is crucial, and you want to leverage PHP's type safety features.

Route::get('/admin', function () {
// ...
})->can(Permission::ACCESS_ADMIN);

Here's how to implement role-based routing in an admin panel:

// app/Enums/AdminAccess.php
 
<?php
 
namespace App\Enums;
 
enum AdminAccess: string
{
case VIEW_REPORTS = 'view_reports';
case MANAGE_STAFF = 'manage_staff';
case EDIT_CONFIG = 'edit_config';
}
 
// web.php
Route::prefix('admin')->group(function () {
Route::get('/reports', ReportController::class)
->can(AdminAccess::VIEW_REPORTS);
 
Route::get('/staff', StaffController::class)
->can(AdminAccess::MANAGE_STAFF);
 
Route::post('/config', ConfigController::class)
->can(AdminAccess::EDIT_CONFIG);
});

The route definitions become more intuitive and maintainable:

// Previous approach
->can(AdminAccess::MANAGE_STAFF->value)
// New, cleaner approach
->can(AdminAccess::MANAGE_STAFF)

The enhanced can() method makes your permission-based routing more elegant while maintaining the benefits of PHP's type system.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

acquaintsoft logo
Acquaint Softtech

Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Visit Acquaint Softtech

The latest

View all →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article