Home > Backend Development > PHP Tutorial > Enum-Powered Route Permissions in Laravel

Enum-Powered Route Permissions in Laravel

Robert Michael Kim
Release: 2025-03-06 01:37:08
Original
769 people have browsed it

Enum-Powered Route Permissions in Laravel

Laravel now simplifies permission checking in routing by directly adding enumeration support in the can() method. This enhancement eliminates the need to explicitly access the value properties of enumerations, making the routing definition simpler and more expressive.

This feature is especially great when building admin panels or multi-tenant applications where permission management is critical and you want to take advantage of PHP's type safety features.

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

The following is how to implement role-based routing in the 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);
});
Copy after login

Routing definitions become more intuitive and easy to maintain:

// 旧方法
->can(AdminAccess::MANAGE_STAFF->value)
// 新方法,更简洁
->can(AdminAccess::MANAGE_STAFF)
Copy after login
The enhanced

method makes your permission-based routing more elegant while retaining the benefits of the PHP type system. can()

The above is the detailed content of Enum-Powered Route Permissions in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template