Prerequisites
- Laravel 5.8 or higher
- User model must implement
Illuminate\Contracts\Auth\Access\Authorizable
contract. Otherwise thecan()
andauthorize()
methods will not work in your controllers, policies, templates, etc. - User model must not have a:
- role or roles property
- roles() method
- permission or permission property
- permission() method
- This package publishes config/permission.php file. If already exist then rename or remove it, as it will conflict with this package.
Installation
- Install package via composer
=>
composer require spatie/laravel-permission
- May automatically registered or you may manually add if not not automatically. Include package to list of service provider in config/app.php
'providers' => [
// ... Spatie\Permission\PermissionServiceProvider::class, ]
;
- Next publish the migration file for this package with the command
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
--tag
="migrations"
- Publish the configuration file for this package by running
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
--tag="config"
-
Use Role and Use Permission in User Model
use Illuminate\Foundation\Auth\User as Authenticatable; use Spatie\Permission\Traits\HasRoles;
use Spatie\Permission\Models\Role; use Spatie\Permission\Models\Permission;
class User extends Authenticatable { ...... use HasRoles; ...... }
-
A role can be created like a regular Eloquent model
$role = Role::create(['name' => 'writer']); $permission = Permission::create(['name' => 'edit articles']);