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);
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); });
Routing definitions become more intuitive and easy to maintain:
// 旧方法 ->can(AdminAccess::MANAGE_STAFF->value) // 新方法,更简洁 ->can(AdminAccess::MANAGE_STAFF)
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!