Best Way To Implement Role And Permissions In Laravel

text

Role Permissions Laravel

Best Way To Implement Role And Permissions In Laravel

Roles and permissions are an important part of many web applications. Most of the organizations use role-based access control to provide their employees with varying levels of access. For example, we can designate whether a user is an administrator, an accountant, an operator or an end-user, and limit access to specific resources or tasks based on their roles and responsibilities. This protects sensitive data and ensures users can only access information and perform actions they are allowed to.

 

To implement Roles and Permission, we use Spatie roles and permissions” package. This package provides an API to deal with roles and permissions more easily. Also, the final code is more reader-friendly and easier to understand.

 

About Spatie Roles permissions 

Spatie role permissions package provides us a way to manage Access control level in Laravel. Using this package we can assign single or multiple roles and permissions to user. We do not need to write rules in Policies or Gates, we just need to call function with required arguments.


DB Structure

This package will create 5 tables in database, which are: 

  1. Roles: In this table we store a list of roles
  2. Permissions: Store list of permissions
  3. Role_has_permissions: Store list of role_id synced with permission_id
  4. Model_has_roles: This table has only 3 columns role_id, model_id and model_type.
    • role_id is a foreign key from roles table
    • model is a foreign key from users table
    • model_type store the path of users model. The default value of model_type column is ‘App/User’, because according to Laravel structure by default users table exist in same location.
  5. Model_has_permissions: This table is used to give direct permission to user, in which permission_id, model_id (foreign key from permissions and users tables) and model_type are stored.


How to use spatie role/permissions:-
 

  1. Install package in project using command  composer require spatie/laravel-permission“.
  2. Open config/app.php file and add service provider and alias into providers array  Spatie\Permission\PermissionServiceProvider::class,
  3. Just after installing package it will create migration file, so next step is to run migration (assuming DB already exist) using command “php artisan migrate”.
  4. Add traits to user model
    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Spatie\Permission\Traits\HasRoles;
    class User extends Authenticatable
    {
       use HasRoles;
        // …
    }
  5. Now we are ready to use functionality of this package. 


Basic methods provided by package

  1. Assign and remove role from user
    $user->assignRole(‘admin’); 
    $user->assignRole([‘admin’, ‘accountant’]);
    $user->removeRole(‘accountant’);
  2. Assign and remove permission from user
    $user->givePermissionTo(‘add customer’); 
    $user->givePermissionTo(‘edit customer’, ‘delete customers’, ‘view customers’);
    $user->revokePermissionTo(‘delete customers’);
  3. Assign and remove permission from role
    $role->syncPermissions([‘add customer’, ‘view customers’]);
  4. Checking user has access or not using middleware
    $this->middleware(‘role:Admin|Operation’, [‘only’ => [‘store’, ‘destroy’]]);
  5. Checking role/permission for a user:
    $user->hasRole(‘technician’); 
    $user->hasAnyRole(Role::all()); 
    $user->hasAllRoles(Role::all());For permisssion:
    $user->can(‘edit customer’); 
    $role->hasPermissionTo(‘edit customer’);
  6. Get all permissions for the user, either directly, or from roles, or from both 
    $user->getDirectPermissions(); 
    $user->getPermissionsViaRoles(); 
    $user->getAllPermissions();
  7. Get user roles
    $user->getRoleNames();

 

More information can be found here

Defining customer centric solutions for greater business value

Boost your business with our innovative thinking

Sales Department:

  India (HQ)

Address: 422B, Tower B, Ithum, Sector-62, Noida, 201301

Phone:   +91 70119 25215

Email:    surajs@dtechnoland.com

  USA

Address: 2532 Santa Clara Ave, Unit #501, Alameda, CA 94501

Phone: +1 (707) 516-6991

Email:    surajs@dtechnoland.com

  UK

Address: 59, St. Martin’s Lane, Unit #147, London, WC2N 4JS

Phone:  +44 20 3667 9345

Email:    surajs@dtechnoland.com

dreamer logo white

Dreamer Technoland is focused on acting as a “True voice” for our clients by delivering innovative solutions that are designed to meet the business needs.

Follow us on


    You have a vision.
    We have a way to get you there.

    700+

    Projects

    Completed

    8+

    Years of

    Experience

    85%

    Long Term

    Clients





    X
    DOWNLOAD BROCHURE