Role based access control using Laravel 5.7 Example

Today, We want to share with you Role based access control using Laravel 5.7 Example.In this post we will show you User Role based Authentication and Access Control in Laravel, hear for Laravel 5.7 User Roles and Permissions (ACL) using Spatie Tutorial we will give you demo and example for implement.In this post, we will learn about Laravel 5.7 Role Based Access Control using Middlewares with an example.

Role based access control using Laravel 5.7 Example

There are the Following The simple About Role based access control using Laravel 5.7 Example Full Information With Example and source code.

As I will cover this Post with live Working example to develop Set-up role based access control in Laravel, so the Laravel 5.7 Users and Roles Management for this example is following below.

Step 1: Setting Up & Migrating the Database:

Add a new role column to our User Table existing user migration:

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('email')->unique();
    $table->string('password');
    $table->string('role');// the Laravel Based role column
    $table->rememberToken();
    $table->timestamps();
});
 

Run laravel migrate specific table:

php artisan migrate

Step 2: Customise the registration form:

authentication scaffolding

Custom Registration Form with Validation

php artisan make:auth

resources/views/auth/register.blade.php

Registration

Step 3: Customize User Model and Register Controller:

User.php

//User.php
protected $fillable = [
    'name', 'email', 'password','role',
];
 

Step 4: Change simple RegisterController.php

app/Http/Controllers/Auth

protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => 'required|string|max:255',
        'email' => 'required|string|email|max:255|unique:users',
        'password' => 'required|string|min:6|confirmed',
        'role' => 'required|in:admin,Employee,Manager', //validate role input
    ]);
}
protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
        'role' => $data['role'],
    ]);
} 

Step 5: Laravel 5.7 Create Custom Middleware:

create middlewares using CLI

php artisan make:middleware Admin
php artisan make:middleware Employee
php artisan make:middleware Manager

Step 6: Laravel middlewares Source code

app/Http/Middleware/Admin.php


use Auth; //at the top

function handle($request, Closure $next)
{
    if (Auth::check() && Auth::user()->role == 'admin') {
        return $next($request);
    }
    elseif (Auth::check() && Auth::user()->role == 'Employee') {
        return redirect('/Employee');
    }
    else {
        return redirect('/Manager');
    }
}

app/Http/Middleware/Employee.php

use Auth; //at the top

function handle($request, Closure $next)
{
    if (Auth::check() && Auth::user()->role == 'Employee') {
        return $next($request);
    }
    elseif (Auth::check() && Auth::user()->role == 'Manager') {
        return redirect('/Manager');
    }
    else {
        return redirect('/admin');
    }
}

app/Http/Middleware/Manager.php


use Auth; //at the top

function handle($request, Closure $next)
{
    if (Auth::check() && Auth::user()->role == 'Manager') {
        return $next($request);
    }
    elseif (Auth::check() && Auth::user()->role == 'Employee') {
        return redirect('/Employee');
    }
    else {
        return redirect('/admin');
    }
}

Step 7: Add the middleware classes to $routeMiddleware

app/Http/Kernel.php

protected $routeMiddleware = [
    // ...
    'admin' => 'App\Http\Middleware\Admin',
    'Employee' => 'App\Http\Middleware\Employee',
    'Manager' => 'App\Http\Middleware\Manager',
];

web.php:


Route::get('/admin', function(){
    echo "Welcome To Admin";
})->middleware('auth','admin');

Route::get('/Employee', function(){
    echo "Welcome To Employee";
})->middleware('auth','Employee');

Route::get('/Manager', function(){
    echo "Welcome To Manager";
})->middleware('auth','Manager');

middleware in a controller’s constructor,

public function __construct()
{
    $this->middleware('auth');  
    $this->middleware('admin');
}

Step 8: Laravel Redirect User After Sign-in:

LoginController.php

protected function redirectTo( ) {
    if (Auth::check() && Auth::user()->role == 'Manager') {
        return redirect('/Manager');
    }
    elseif (Auth::check() && Auth::user()->role == 'Employee') {
        return redirect('/Employee');
    }
    else {
        return redirect('/admin');
    }
}

Bonus For Implementing Roles & Permissions in Laravel

Roles and permissions database migrations

items

Column Type Null Default Links to
id (Primary) int(10) No
title varchar(255) No
description text No
created_at timestamp Yes NULL
updated_at timestamp Yes NULL

Indexes

Role based access control No index defined!
Keyname Type Unique Packed Column Cardinality Collation Null Comment
PRIMARY BTREE Yes No id 0 A No

migrations

Column Type Null Default Links to
id (Primary) int(10) No
migration varchar(255) No
batch int(11) No

Indexes

Role based access control No index defined!
Keyname Type Unique Packed Column Cardinality Collation Null Comment
PRIMARY BTREE Yes No id 4 A No

password_resets

Column Type Null Default Links to
email varchar(255) No
token varchar(255) No
created_at timestamp Yes NULL

permissions

Column Type Null Default Links to
id (Primary) int(10) No
name varchar(255) No
display_name varchar(255) Yes NULL
description varchar(255) Yes NULL
created_at timestamp Yes NULL
updated_at timestamp Yes NULL

Indexes

Role based access control No index defined!
Keyname Type Unique Packed Column Cardinality Collation Null Comment
PRIMARY BTREE Yes No id 8 A No

permission_role

Column Type Null Default Links to
permission_id (Primary) int(10) No permissions -> id
role_id (Primary) int(10) No roles -> id

Indexes

Role based access control No index defined!
Keyname Type Unique Packed Column Cardinality Collation Null Comment
PRIMARY BTREE Yes No permission_id 5 A No
role_id 5 A No
permission_role_role_id_foreign BTREE No No role_id 2 A No

roles

Column Type Null Default Links to
id (Primary) int(10) No
name varchar(255) No
display_name varchar(255) Yes NULL
description varchar(255) Yes NULL
created_at timestamp Yes NULL
updated_at timestamp Yes NULL

Indexes

Role based access control No index defined!
Keyname Type Unique Packed Column Cardinality Collation Null Comment
PRIMARY BTREE Yes No id 2 A No

role_user

Column Type Null Default Links to
user_id (Primary) int(10) No users -> id
role_id (Primary) int(10) No roles -> id

Indexes

Role based access control No index defined!
Keyname Type Unique Packed Column Cardinality Collation Null Comment
PRIMARY BTREE Yes No user_id 2 A No
role_id 2 A No
role_user_role_id_foreign BTREE No No role_id 2 A No

users

Column Type Null Default Links to
id (Primary) int(10) No
name varchar(255) No
email varchar(255) No
password varchar(255) No
remember_token varchar(100) Yes NULL
created_at timestamp Yes NULL
updated_at timestamp Yes NULL

Indexes

Role based access control No index defined!
Keyname Type Unique Packed Column Cardinality Collation Null Comment
PRIMARY BTREE Yes No id 0 A No
Angular 6 CRUD Operations Application Tutorials

Read :

Summary

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

I hope you get an idea about Role based access control using Laravel 5.7 Example.
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.

Leave a Comment