Wallogit.com
2017 © Pedro Peláez
Roles and Permissions for Laravel 5
This package is designed to provide a very basic roles and permissions structure for Laravel 5., (*1)
To install this roles package, you must use Composer. Type the following in your Command Line Interface, (*2)
composer require dcastanera/laravel-roles
This should install all the roles files to your vendors directory., (*3)
Next we want to register the service provider in the /config/app.php file. Go to the array for providers and enter the following:, (*4)
DCastanera\Roles\RolesServiceProvider::class,
Now we want to bring in the migrations by typing the following:, (*5)
php artisan vendor:publish
The above command copied a new migration into your migrations folder so now we need to run a migration., (*6)
php artisan migrate
In order for the roles to attach to the user, we need to add the Roleable trait in the user model. Add the following to the top of the user model to include the trait., (*7)
use DCastanera\Roles\Roleable;
Then add the following inside the class after use notifiable., (*8)
use Roleable;
You should be all set after that., (*9)
To use Roles you need to make sure you reference the Roles model., (*10)
use DCastanera\Roles\Role;
To create a role you can try the following:, (*11)
$role = new Role; $role->name = 'Super Administrator'; $role->slug = 'super'; $role->description = 'This is the Super Administrator role.'; $role->save();
or you can also use the create method:, (*12)
$role = Role::create([
'name' => 'Administrator',
'slug' => 'admin',
'description' => 'This is the system Administrator.',
]);
both should function the same., (*13)
To attach a role to a user, we simply need to call both objects and save them using the eloquent roles method as follows:, (*14)
// First grab the user object $user = User::find(1); // Next grab the role object $role = Role::find(1); // Use the following to attach them. $user->roles()->save($role);
To detach a role from a user, we simply need to call both objects and delete the role from the roles method as follows:, (*15)
// First grab the user object $user = User::find(1); // Next grab the role object $role = Role::find(1); // Use the following to detach them. $user->roles()->delete($role);