DEV Community

Er Amit Gupta
Er Amit Gupta

Posted on • Edited on

Zero Configuration laravel Role Permission Setup πŸ”₯🀩

Screenshot 2024-10-04 at 10 34 23β€―PM

Packagist License
Latest Stable Version
Total Downloads

This package provides an effortless way to manage roles and permissions in your Laravel application. With automatic database configuration, one-command publishing, and easy integration, you can quickly set up robust role-based access control without hassle.

Getting Started

composer require erag/laravel-role-permission 
Enter fullscreen mode Exit fullscreen mode

Step 1: Add Trait to User Model

Before configuring the database and publishing the role-permission files, add the HasPermissionsTrait to define in your User model. This trait is essential for handling roles and permissions in your application.

HasPermissionsTrait 
Enter fullscreen mode Exit fullscreen mode
<?php namespace App\Models; use EragPermission\Traits\HasPermissionsTrait; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; class User extends Authenticatable { use HasFactory, HasPermissionsTrait, Notifiable; } 
Enter fullscreen mode Exit fullscreen mode

Step 2: Database Configuration

Before proceeding with the setup, ensure that your database connection is properly configured in your .env file. Example configuration:

DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=your_database_name DB_USERNAME=your_database_user DB_PASSWORD=your_database_password 
Enter fullscreen mode Exit fullscreen mode

Make sure to replace your_database_name, your_database_user, and your_database_password with your actual database credentials.

Step 3: Automatic Database Setup

After configuring your database connection, the package will automatically set up your database by running the necessary migrations and seeders without any additional setup.

Step 4: Register the Service Provider

For Laravel v11.x

Ensure the service provider is registered in your /bootstrap/providers.php file:

return [ // ... EragPermission\PermissionServiceProvider::class, ]; 
Enter fullscreen mode Exit fullscreen mode

For Laravel v10.x

Ensure the service provider is registered in your config/app.php file:

'providers' => [ // ... EragPermission\PermissionServiceProvider::class, ], 
Enter fullscreen mode Exit fullscreen mode

Step 5: Publish Role-Permission Files

Once the database is configured, publish the required migration and model files with a single command:

php artisan erag:publish-permission 
Enter fullscreen mode Exit fullscreen mode

This command will publish the required migrations:

php artisan erag:publish-permission --migrate 
Enter fullscreen mode Exit fullscreen mode

If you want to run the published migrations and seed the datbase you cann add --migrate and --seed respectively. Then the command will automatically run the migrations and the seeder to set up roles and permissions in your database.

php artisan erag:publish-permission --migrate --seed 
Enter fullscreen mode Exit fullscreen mode

Step 6: Using Role-Based Permissions

You can now easily check user permissions within your application logic:

if (auth()->user()->can('permission_name')) { // The user has the specified permission } 
Enter fullscreen mode Exit fullscreen mode

You can also use the helper method:

if (hasPermissions('post-create')) { dd('You are allowed to access'); } else { dd('You are not allowed to access'); } 
Enter fullscreen mode Exit fullscreen mode

OR

if (hasPermissions('post-create|post-edit')) { dd('You are allowed to access'); } else { dd('You are not allowed to access'); } if (hasPermissions('post-create,post-edit')) { dd('You are allowed to access'); } else { dd('You are not allowed to access'); } 
Enter fullscreen mode Exit fullscreen mode

To get all permissions:

getPermissions(); 
Enter fullscreen mode Exit fullscreen mode

Using Role-Based Checks

if (hasRole('admin')) { dd('You are allowed to access'); } else { dd('You are not allowed to access'); } 
Enter fullscreen mode Exit fullscreen mode

To get all roles:

getRoles(); 
Enter fullscreen mode Exit fullscreen mode

Step 7: Protecting Routes with Middleware

To protect routes based on roles and permissions, you can use the provided middleware. For example, to allow only users with the user role and create-user permission:

 Route::group(['middleware' => ['role:user,user-create']], function () { // Protected routes go here }); Route::group(['middleware' => ['role:admin,post-create']], function () { // Protected routes go here }); 
Enter fullscreen mode Exit fullscreen mode

Step 8: Displaying Content Based on Roles

You can also use Blade directives to display content based on the user's role:

@role('admin') {{ __('You are an admin') }} @endrole @role('user') {{ __('You are a user') }} @endrole 
Enter fullscreen mode Exit fullscreen mode

Step 9: Displaying Content Based on Permissions

You can also use Blade directives to display content based on the user's permissions:

@hasPermissions('post-create') {{ __('You can create a post') }} @endhasPermissions 
Enter fullscreen mode Exit fullscreen mode

OR

@hasPermissions('post-create|post-edit') {{ __('You can create a post') }} @endhasPermissions @hasPermissions('post-create,post-edit') {{ __('You can create a post') }} @endhasPermissions 
Enter fullscreen mode Exit fullscreen mode

Example Seeder for Roles and Permissions

Here's an example RolePermissionSeeder that seeds roles, permissions, and users:

<?php namespace Database\Seeders; use App\Models\User; use EragPermission\Models\Role; use EragPermission\Models\Permission; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Hash; class RolePermissionSeeder extends Seeder { /** * Run the database seeds. */ public function run(): void { DB::transaction(function () { $this->seedPermissions(); $this->seedRoles(); $this->seedUsers(); }); } private function seedPermissions(): void { $permissions = [ 'post-create', 'user-create', ]; foreach ($permissions as $permissionName) { Permission::firstOrCreate(['name' => $permissionName]); } } private function seedRoles(): void { $roles = [ 'admin' => ['post-create', 'post-edit', 'post-delete', 'post-update'], 'user' => ['user-create', 'user-edit', 'user-delete', 'user-update'], ]; foreach ($roles as $roleName => $permissionNames) { $role = Role::firstOrCreate(['name' => $roleName]); foreach ($permissionNames as $permissionName) { $permission = Permission::firstOrCreate(['name' => $permissionName]); $role->permissions()->syncWithoutDetaching($permission); $permission->roles()->syncWithoutDetaching($role); } } } private function seedUsers(): void { $users = [ [ 'name' => 'Admin', 'email' => 'admin@gmail.com', 'password' => Hash::make('admin'), 'roles' => ['admin'], 'permissions' => ['post-create', 'post-edit'], ], [ 'name' => 'User', 'email' => 'user@gmail.com', 'password' => Hash::make('user'), 'roles' => ['user'], 'permissions' => ['user-create', 'user-edit'], ], ]; foreach ($users as $userData) { $user = User::updateOrCreate( ['email' => $userData['email']], [ 'name' => $userData['name'], 'password' => $userData['password'], ] ); foreach ($userData['roles'] as $roleName) { $role = Role::where('name', $roleName)->first(); if ($role) { $user->roles()->syncWithoutDetaching($role); } } foreach ($userData['permissions'] as $permissionName) { $permission = Permission::where('name', $permissionName)->first(); if ($permission) { $user->permissions()->syncWithoutDetaching($permission); } } } } } 
Enter fullscreen mode Exit fullscreen mode

Contribution πŸ§‘β€πŸ’»

We welcome contributions to this project. Please read our Contributing Guidelines before you start contributing.

Top comments (0)