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
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
<?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;
}
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
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,
];
For Laravel v10.x
Ensure the service provider is registered in your config/app.php
file:
'providers' => [
// ...
EragPermission\PermissionServiceProvider::class,
],
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
This command will publish the required migrations:
php artisan erag:publish-permission --migrate
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
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
}
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');
}
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');
}
To get all permissions:
getPermissions();
Using Role-Based Checks
if (hasRole('admin')) {
dd('You are allowed to access');
} else {
dd('You are not allowed to access');
}
To get all roles:
getRoles();
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
});
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
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
OR
@hasPermissions('post-create|post-edit')
{{ __('You can create a post') }}
@endhasPermissions
@hasPermissions('post-create,post-edit')
{{ __('You can create a post') }}
@endhasPermissions
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);
}
}
}
}
}
Contribution π§βπ»
We welcome contributions to this project. Please read our Contributing Guidelines before you start contributing.
Top comments (0)