Laravel User Role based Authentication and Access Control (ACL) -- Any Version

Read In Also

We are using Laravel Any Version for this tutorial.

Role-Based Authentication / Authorization (ACL)


To showcase the Laravel Role-Based Authentication. Let's create three sections in the application one is "SuperAdmin", "Admin" and another is "User". After user is logged in they require a specific role privilege to enter this area of Laravel Application

Setup Laravel Authentication (Any Laravel Version)

Download easy To Link


You don't have to understand laravel defuat auth system follow link
---------

Create Controllers

Let’s create Three new controller’s SuperAdminController, AdminController and UserController
php artisan make:controller SuperAdminController
php artisan make:controller AdminController
php artisan make:controller UserController

Add index method to Three the controller
    //Index method for SuperAdmin Controller
    public function index()
    {
        return view('superadmin.home');
    }
    //Index method for Admin Controller
    public function index()
    {
        return view('admin.home');
    }
    //Index method for User Controller
    public function index()
    {
        return view('user.home');
    }

index method for SuperAdmin Controller returns the home page which is in superadmin view folder.

index method from AdminController returns the home page from admin folder

index method from UserController returns the home page from User folder

Create Views

Create new folder superadmin under resources > views and add new file home.blade.php
@extends('layouts.app')
@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Super Admin Dashboard</div>

                <div class="panel-body">
                    @if (session('status'))
                        <div class="alert alert-success">
                            {{ session('status') }}
                        </div>
                    @endif

                        This is Super Admin Dashboard. You must be super privileged to be here !
                </div>
            </div>
        </div>
    </div>
</div>
@endsection


Next,Create new folder admin under resources > views and add new file home.blade.php



@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Admin Dashboard</div>

                <div class="panel-body">
                    @if (session('status'))
                        <div class="alert alert-success">
                            {{ session('status') }}
                        </div>
                    @endif

                    This is Admin Dashboard. You must be privileged to be here !
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Next,Create new folder user under resources > views and add new file home.blade.php



@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">UserDashboard</div>

                <div class="panel-body">
                    @if (session('status'))
                        <div class="alert alert-success">
                            {{ session('status') }}
                        </div>
                    @endif

                    This is User Dashboard. You must be privileged to be here !
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Create Routes

Route::get('/superadmin', 'SuperAdminController@index');
Route::get('/admin', 'AdminController@index');
Route::get('/user', 'UserController@index');

Create Model

php artisan make:model Role -m

Role Model

This will create a Model class for the roles table and will also create a migrations file under database > migrations


Edit the "CreateRolesTable" class under migrations folder


<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateRolesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('roles');
    }
}

Create Migration for the role_user table

php artisan make:migration create_role_user_table

Edit the "CreateRoleUserTable" class in the migrations folder:


<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateRoleUserTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('role_user', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('role_id')->unsigned();
            $table->integer('user_id')->unsigned();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('role_user');
    }
}

Next, we need to provide many-to-many relationship between User and Role Add roles() method to your User.php class

  public function roles()
    {
        return $this
            ->belongsToMany('App\Role')
            ->withTimestamps();
    }

Add users() to your Role.php class

 public function users()
    {
        return $this
            ->belongsToMany('App\User')
            ->withTimestamps();
    }

Create Seeder

Link

Modify User.php 

Just a few more steps, Don’t give up ! Open user.php and add these tiny methods which will be used to check if user has a particular role or roles

public function authorizeRoles($roles)
{
  if ($this->hasAnyRole($roles)) {
    return true;
  }
  abort(401, 'This action is unauthorized.');
}
public function hasAnyRole($roles)
{
  if (is_array($roles)) {
    foreach ($roles as $role) {
      if ($this->hasRole($role)) {
        return true;
      }
    }
  } else {
    if ($this->hasRole($roles)) {
      return true;
    }
  }
  return false;
}
public function hasRole($role)
{
  if ($this->roles()->where(‘name’, $role)->first()) {
    return true;
  }
  return false;
}

With the above methods, if you are looking to check just against a single role you can make use of hasRole method.

Or You can check against multiple roles by passing an array to "authorizeRoles" method.

Create Middleware

We will create a new middleware "CheckRole"

php artisan make:middleware CheckRole

Modify the CheckRole.php file under app > Middleware

<?php

namespace App\Http\Middleware;

use Closure;

class CheckRole
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $role)
    {
        if (! $request->user()->hasRole($role)) {
            abort(401, 'This action is unauthorized.');
        }
        return $next($request);
    }
}

We have modified the handle method middleware to check for given role. Next step is to register the middleware we just created. Open "Kernal.php" which is located under App > and modify array $routeMiddleware" to include the role middleware.

protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'role' => \App\Http\Middleware\CheckRole::class,
    ];

Modify Controllers

Open AdminController.php. Below code in constructor method will check if the logged in user has role ROLE_ADMIN associated with it.

 public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('role:ROLE_ADMIN');
    }

same for SuperAdminController.php

public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('role:ROLE_SUPERADMIN');
    }

same for UserAdminController.php

public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('role:ROLE_USER');
    }

That’s it !  Only privileged user can access the certain parts of your application.


Keywords:-

laravel 5.8 roles and permissions
spatie/laravel-permission packagist
laravel entrust
laravel route middleware permission
spatie laravel permission documentation
laravel access control
laravel best authentication package
simple role permission laravel
permission management
assign roles in laravel
different user roles in laravel
laravel user roles and permissions
authorization in laravel
trust laravel
create user role in laravel
laravel authorization tutorial
laravel multiple user roles
laravel blade @role
laravel 6.0 roles and permissions
role level laravel
role based authorization in laravel
laravel entrust tutorial
has role laravel
laravel roles permissions crud
how to check user role in laravel
role based access control php mysql
laravel ACL

No comments

Note: only a member of this blog may post a comment.