Laravel Spatie – Role Permission

Prerequisites

  1. Laravel 5.8 or higher
  2. User model must implement Illuminate\Contracts\Auth\Access\Authorizable contract. Otherwise the can() and authorize() methods will not work in your controllers, policies, templates, etc.
  3. User model must not have a:
    1. role or roles property
    2. roles() method
    3. permission or permission property
    4. permission() method
  4. This package publishes config/permission.php file. If already exist then rename or remove it, as it will conflict with this package.

Installation

  1. Install package via composer =>
    composer require spatie/laravel-permission
  2. 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, ]
    ;
  3. Next publish the migration file for this package with the command
    php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --tag="migrations"
  4. Publish the configuration file for this package by running
    php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --tag="config"
  5. 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; 
    ......
    }
  6. A role can be created like a regular Eloquent model
    $role = Role::create(['name' => 'writer']);
    $permission = Permission::create(['name' => 'edit articles']);
    
    

Leave a Reply

Your email address will not be published. Required fields are marked *