Install the package via Composer
composer require erag/laravel-role-permission
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;
}
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.
Ensure the service provider is registered in your /bootstrap/providers.php
file:
return [
// ...
EragPermission\PermissionServiceProvider::class,
];
Ensure the service provider is registered in your config/app.php
file:
'providers' => [
// ...
EragPermission\PermissionServiceProvider::class,
],
Once the database is configured, publish the required migration with a single command:
php artisan erag:publish-permission
You can also run migrations and seeders:
php artisan erag:publish-permission --migrate
Or both
php artisan erag:publish-permission --migrate --seed
To upgrade the package to a new version:
php artisan erag:upgrade-version
You can now easily check user permissions within your application logic: 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');
}
Retrieve Permissions and Roles
getPermissions();
getRoles();
if (hasRole('admin')) {
dd('You are allowed to access');
} else {
dd('You are not allowed to access');
}
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
});
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
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
The permission expiration feature allows you to set temporary access that expires automatically after a certain period or, by setting the expiration date to null, to allow unlimited access. This feature is useful for setting up both temporary and permanent permissions.
-
Assign Permission with Expiration: Use the
givePermissionsTo
method to assign a permission with an expiration date.// Assign a permission with a specific expiration date $user->givePermissionsTo(['post-create', 'post-edit'], Carbon::now()->addDays(30), // Each Permission expiration assign in 30 days );
In this example, the
post-create
permission will be assigned to the user and expire after 30 days. -
Assign Multiple Permissions with Different Expirations: If you need to assign multiple permissions with individual expiration dates, pass an associative array where the keys are permission names, and the values are the expiration dates.
$user->givePermissionsTo(['post-create', 'post-edit'], [ Carbon::now()->addDays(10), // Expires in 10 days Carbon::now()->addHours(6), // Expires in 6 hours ]);
1Assign Permission with Unlimited Duration: Assign permissions without an expiration by setting the expiration to null
. This will give the user unlimited access to the permission.
// Assign a permission with a specific expiration date
$user->givePermissionsTo(['post-create'],
null, // [] Array or String
);
OR
$user->givePermissionsTo(['post-create', 'post-edit']);
Each permission will be stored with its own expiration time, allowing for granular control over each access level.
The package automatically checks for expiration when evaluating a userβs permissions. You can use the hasRole
, @role
OR hasPermissions
, @hasPermissions
helper methods to check if a permission is still active:
Here's an example RolePermissionSeeder
that seeds roles, permissions, and users:
<?php
namespace Database\Seeders;
use App\Models\User;
use Carbon\Carbon;
use EragPermission\Models\Permission;
use EragPermission\Models\Role;
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->seedRolePermissions();
$this->seedUsers();
});
}
/**
* Seed role permissions.
*/
private function seedRolePermissions(): void
{
$rolePermission = [
'admin' => ['post-create', 'post-edit', 'post-delete', 'post-update'],
'user' => ['user-create', 'user-edit', 'user-delete', 'user-update'],
];
foreach ($rolePermission as $role => $permissions) {
$role = Role::create(['name' => $role]);
foreach ($permissions as $permission) {
$permission = Permission::create(['name' => $permission]);
$role->permissions()->attach($permission);
}
}
}
private function seedUsers(): void
{
$users = [
[
'name' => 'Admin',
'email' => 'admin@gmail.com',
'password' => Hash::make('admin'),
'roles' => ['admin'],
'permissions' => [
'post-create' => Carbon::now()->addDays(30),
'post-edit' => Carbon::now()->addMinutes(60),
],
],
[
'name' => 'User',
'email' => 'user@gmail.com',
'password' => Hash::make('user'),
'roles' => ['user'],
'permissions' => [
'user-create' => Carbon::now()->addDays(30),
'user-edit' => null,
],
],
];
foreach ($users as $userData) {
$user = User::updateOrCreate(
['email' => $userData['email']],
[
'name' => $userData['name'],
'password' => $userData['password'],
]
);
$user->assignRole($userData['roles']);
$permissionsWithExpiry = $userData['permissions'];
$user->givePermissionsTo(array_keys($permissionsWithExpiry), $permissionsWithExpiry);
// $user->givePermissionsTo(array_keys($permissionsWithExpiry), Carbon::now()->addDays(30));
}
}
}
We welcome contributions to this project. Please read our Contributing Guidelines before you start contributing.