Laravel 12 - Role-Based Permissions and Controller
This PHP code defines a simple role-based permission system that allows different user roles to perform different actions within a Laravel 12 application. It uses a configuration file to manage roles and their corresponding permissions.
Roles and Permissions Configuration:
The roles
configuration (defined in config/roles.php
) maps each user role to specific permissions:
-
Admin has permissions to
view
,edit
, anddelete
. -
Editor has permissions to
view
andedit
. -
User has permission to only
view
.
Controller Usage:
In the controller, we retrieve the current authenticated user's role using Auth::user()->role
. Based on this role, we fetch the corresponding permissions from the roles
configuration.
For each action (view, edit, delete), the code checks if the current user has the required permission. If they do, an appropriate button is displayed in the HTML. Here's the logic:
-
View permission: All roles can view, so a "view" button is displayed for everyone.
-
Edit permission: Only Admin and Editor roles can edit, so the "edit" button is shown to users with these roles.
-
Delete permission: Only Admin can delete, so the "delete" button is shown only for Admin users.
The buttons are structured with Bootstrap and icons for the following actions:
-
View: Opens a modal to view the user details.
-
Edit: Opens an offcanvas form to edit the user.
-
Delete: Opens a confirmation modal to delete the user.
Example Controller Code:
How It Works:
-
Dynamic Button Display: Only the relevant action buttons will be shown on the front end, depending on the user's role and permissions.
-
Security: This approach ensures that users are only shown buttons for actions they are authorized to perform.
-
Scalability: The configuration-based approach makes it easy to add new roles and permissions without altering the core application logic.
This is an efficient way to implement role-based access control (RBAC) within a Laravel application, ensuring that users only have access to the functionalities they are permitted to use.