Have two options to install, you can choose one of them
-
Copy this folder
heroderole
tomodules/heroderole
into your root project -
Open file
composer.json
and edit
{
//...
"require": {
"herode/role": "*@dev",
},
"repositories": [
//...
{
"type": "path",
"url": "./modules/heroderole"
}
]
//...
}
composer require herode/role
Next, run: composer update
You can publish the migrations, configure, seeds vie command:
php artisan herode-role:install
After the migrations published you can create the roles tables by running the migrations:
php artisan migrate
When published, The config/herode-roles.php
config file contains:
return [
'models' => [
/*
* Herode roles model
*/
'role' => Herode\Role\Role::class,
],
'table_names' => [
'role' => 'roles'
],
];
First, add the Herode\Role\Contracts\HasRoles
trait to your User
model:
use Herode\Role\Contracts\HasRoles;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasRoles;
// ...
}
Create a role:
$role = Role::create(['name' => 'admin', 'description' => 'Administrator']);
A role can be assign from user:
$user->assignRole($role);
You can check if user has a role:
$user->hasRole('admin')
Remove role from user:
$user->removeRole('admin')
You can published role default seeder via seed command:
php artisan db:seed --class=RoleDefaultSeeder
This package comes with RoleMiddleware
middleware. You can add them inside your app/Http/Kernel.php
file:
protected $routeMiddleware = [
//...
'role' => \Herode\Role\Middlewares\RoleMiddleware::class,
];
Then you can protect your routes using middleware rules:
Route::middleware(['role:admin'])->group(function () {
//...
});
Route::middleware(['role:admin|company'])->group(function () {
//...
});
If you want to override the default 403 response, You can catch the UnauthorizedException
using your app's exception handler:
public function render($request, Exception $exception)
{
if ($exception instanceof Herode\Role\Exceptions\UnauthorizedException) {
// Code here ...
}
return parent::render($request, $exception);
}