Laravel Redirect To Another URL / Web Page - HTTP Laravel Redirects

Laravel Role based permission ACL Tutorial

Today, We want to share with you Laravel Role based permission ACL Tutorial.In this post we will show you laravel user roles and permissions tutorial, hear for Laravel Permissions User Role based access control we will give you demo and example for implement.In this post, we will learn about Laravel Nova Permissions (Roles and Permission based Access Control (ACL)) with an example.

Laravel Role based permission ACL Tutorial

There are the Following The simple About Laravel Role based permission ACL Tutorial Full Information With Example and source code.

As I will cover this Post with live Working example to develop laravel 5.7 user roles and permissions, so the some laravel 5.7 roles and permissions for this example is following below.

Laravel Setting Up

create a new Laravel Application

$ laravel new roles-permissions

Laravel 5.7 Authentication

Authentication scaffolding

$ php artisan make:auth

Models & Migrations

creating the required models and migrations, migrate the database

//creating the required models and migrations
$ php artisan make:model Permission -m
$ php artisan make:model Role -m

//migrate the database
$ php artisan migrate

Permission migration file

set of fields for Roles and Permission based Access Control (ACL)

Schema::create('permissions', function (Blueprint $table) {
    $table->increments('id');
    $table->string('slug'); //edit-posts
    $table->string('name'); // edit posts
    $table->timestamps();
});

Role migration file

set of fields

    Schema::create('roles', function (Blueprint $table) {
        $table->increments('id');
        $table->string('slug'); //tester-elc
        $table->string('name'); //tester-elc
        $table->timestamps();
    });

Adding pivot tables

create a new migration, pivot table between users and permissions, create a pivot table for users_roles, users_permissions table,

$ php artisan make:migration create_users_permissions_table --create=users_permissions

//pivot table between users and permissions
Schema::table('users_permissions', function (Blueprint $table) {
    $table->integer('user_id')->unsigned();
    $table->integer('permission_id')->unsigned();

 //FOREIGN KEY CONSTRAINTS
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->foreign('permission_id')->references('id')->on('permissions')->onDelete('cascade');
 
//SETTING THE PRIMARY KEYS
    $table->primary(['user_id','permission_id']);
});

//create a pivot table for users_roles
$ php artisan make:migration create_users_roles_table --create=users_roles

//users_permissions table
Schema::create('users_roles', function (Blueprint $table) {
   $table->integer('user_id')->unsigned();
   $table->integer('role_id')->unsigned();

 //FOREIGN KEY CONSTRAINTS
   $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
   $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');

 //SETTING THE PRIMARY KEYS
   $table->primary(['user_id','role_id']);
});

//roles_permissions 
$ php artisan make:migration create_roles_permissions_table --create=roles_permissions

Schema::create('roles_permissions', function (Blueprint $table) {
 $table->integer('role_id')->unsigned();
 $table->integer('permission_id')->unsigned();

 //FOREIGN KEY CONSTRAINTS
 $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
 $table->foreign('permission_id')->references('id')->on('permissions')->onDelete('cascade');

 //SETTING THE PRIMARY KEYS
 $table->primary(['role_id','permission_id']);
});

Laravel Migration

$ php artisan migrate

Setting up the relationships

Role.php

//Role.php
public function permissions() {
   return $this->belongsToMany(Permission::class,'roles_permissions');
}

Permission.php

//Permission.php
public function roles() {
   return $this->belongsToMany(Role::class,'roles_permissions');
}

Creating a Trait

Permissions/HasPermissionsTrait.php

<?php
namespace App\Permissions;

use App\Permission;
use App\Role;

trait HasPermissionsTrait {

   public function roles() {
      return $this->belongsToMany(Role::class,'users_roles');

   }

   public function permissions() {
      return $this->belongsToMany(Permission::class,'users_permissions');

   }
}

User hasRole

HasPermissionsTrait.php

public function hasRole( ... $roles ) {
   foreach ($roles as $role) {
      if ($this->roles->contains('slug', $role)) {
         return true;
      }
   }
   return false;
}

$user = $request->user();
dd($user->hasRole('admin','editor'));

Checking Permissions

HasPermissionsTrait.php

protected function hasPermissionTo($permission) {
   return $this->hasPermission($permission);
}

protected function hasPermission($permission) {
   return (bool) $this->permissions->where('slug', $permission->slug)->count();
}

Create a new PermissionsServiceProvider for authorization

$ php artisan make:provider PermissionsServiceProvider

PermissionsServiceProvider.php

//PermissionsServiceProvider.php 
public function boot()
 {
     Permission::get()->map(function($permission){
Gate::define($permission->slug, function($user) use ($permission){
   return $user->hasPermissionTo($permission);
});
     });
 }

HasPermissionsTrait.php

public function hasPermissionThroughRole($permission) {
   foreach ($permission->roles as $role){
      if($this->roles->contains($role)) {
         return true;
      }
   }
   return false;
}

public function hasPermissionTo($permission) {
   return $this->hasPermissionThroughRole($permission) || $this->hasPermission($permission);
}

Giving Permissions

HasPermissionsTrait.php

//HasPermissionsTrait.php
public function givePermissionsTo(... $permissions) {
   $permissions = $this->getAllPermissions($permissions);
   dd($permissions);
   if($permissions === null) {
      return $this;
   }
   $this->permissions()->saveMany($permissions);
   return $this;
}

Deleting Permissions

HasPermissionsTrait.php

//HasPermissionsTrait.php
public function deletePermissions( ... $permissions ) {
   $permissions = $this->getAllPermissions($permissions);
   $this->permissions()->detach($permissions);
   return $this;
}

Add the Seeders

create seeders for permissions, roles & users

$ php artisan make:seeder PermissionTableSeeder
$ php artisan make:seeder RoleTableSeeder
$ php artisan make:seeder UserTableSeeder

UserTableSeeder.php

//UserTableSeeder.php
$tester_role = Role::where('slug','tester')->first();
$agent_role = Role::where('slug', 'agent')->first();
$dev_perm = Permission::where('slug','create-tasks')->first();
$agent_perm = Permission::where('slug','edit-users')->first();

$tester = new User();
$tester->name = 'info Muneer';
$tester->email = '[email protected]';
$tester->password = bcrypt('secret');
$tester->save();
$tester->roles()->attach($tester_role);
$tester->permissions()->attach($dev_perm);


$agent = new User();
$agent->name = 'admin Butt';
$agent->email = '[email protected]';
$agent->password = bcrypt('secret');
$agent->save();
$agent->roles()->attach($agent_role);
$agent->permissions()->attach($agent_perm);

RoleTableSeeder.php

$dev_permission = Permission::where('slug','create-tasks')->first();
$agent_permission = Permission::where('slug', 'edit-users')->first();

//RoleTableSeeder.php
$tester_role = new Role();
$tester_role->slug = 'tester';
$tester_role->name = 'Front-end tester';
$tester_role->save();
$tester_role->permissions()->attach($dev_permission);

$agent_role = new Role();
$agent_role->slug = 'agent';
$agent_role->name = 'Assistant agent';
$agent_role->save();
$agent_role->permissions()->attach($agent_permission);

//PermissionTableSeeder.php

//PermissionTableSeeder.php
$tester_role = Role::where('slug','tester')->first();
$agent_role = Role::where('slug', 'agent')->first();

$projectMake = new Permission();
$projectMake->slug = 'create-tasks';
$projectMake->name = 'Create Tasks';
$projectMake->save();
$projectMake->roles()->attach($tester_role);

$usersEdit = new Permission();
$usersEdit->slug = 'edit-users';
$usersEdit->name = 'Edit Users';
$usersEdit->save();
$usersEdit->roles()->attach($agent_role);

run our migration with the –seed flag.

$ php artisan migrate:refresh --seed

test this out in your routes files

$user = $request->user();
dd($user->hasRole('tester')); 
dd($user->givePermissionsTo('create-tasks')); 
dd($user->can('create-tasks')); 

Setting up the Laravel Custom Blade Directives

PermissionsServiceProvider.php

  Blade::directive('role', function ($role){
   return "<?php if(auth()->check() && auth()->user()->hasRole({$role})) :";
  });
  Blade::directive('endrole', function ($role){
   return "<?php endif; ?>";
  });

Laravel Blade view files

@role('admin')
<h1>Hello from the admin</h1>
<p>Welcome to Admin Page</p>
@endrole

Setup the Laravel Middleware

$ php artisan make:middleware RoleMiddleware

Laravel Register kernel & setup

public function handle($request, Closure $next, $role, $permission = null)
 {
   if(!$request->user()->hasRole($role)) {
     abort(404);
  }
  if($permission !== null && !$request->user()->can($permission)) {
      abort(404);
  }
     return $next($request);
 }

Laravel Define a routes

Route::group(['middleware' => 'role:admin'], function() {
   Route::get('/admin', function() {
      return 'Welcome To Admin';
   });
});

Angular 6 CRUD Operations Application Tutorials

Read :

  Laravel 6 User Roles and Permissions Tutorial

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about Laravel Role based permission ACL Tutorial.
I would like to have feedback on my Pakainfo.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.