Home » Laravel Roles Permissions Example Tutorial From Scratch

Laravel Roles Permissions Example Tutorial From Scratch

Today, We want to share with you Laravel Roles Permissions Example Tutorial From Scratch.In this post we will show you Set-up role based access control in Laravel, hear for Implementing Roles & Permissions in Laravel we will give you demo and example for implement.In this post, we will learn about Laravel Manage User Roles And Permissions with an example.

Laravel Roles Permissions Example Tutorial From Scratch

There are the Following The simple About Laravel Roles Permissions Example Tutorial From Scratch Full Information With Example and source code.

As I will cover this Post with live Working example to develop LARAVEL 5 USERS AND ROLES MANAGEMENT, so the some major files and Directory structures for this example is following below.

  • Buid a Laravel migrations
  • Add a Form Select Box the registration form
  • Changes User Model
  • Changes Register Controller
  • Customization of the middlewares

Step 1 : Buid a Laravel migrations:

First of all You Include a new fields role column to our application existing user migration

Implementing Roles & Permissions in Laravel Migrations

//Create laravel user roles and permissions Database Migrations
Schema::create('users', function (Blueprint $table) {
    $table->increments('id');  // Uniq id
    $table->string('name');   // User name
    $table->string('email')->unique();
    $table->string('password');  // default Password
    $table->string('role');// the simple role column Adds
    $table->rememberToken();
    $table->timestamps(); //Created and updated time and date store
});

Run the Database migrations to Create the tables:

Read Also:  Laravel 6 User Roles and Permissions Tutorial

Run Below Commands

php artisan migrate

Step 2 : Add a Form Select Box the registration form

Now, simple Create the authentication Based scaffolding(Set-up role based access control in Laravel) which comes Main Data bundled with Laravel. and then run bellow commands.

Customize the registration form

php artisan make:auth

After That, You Some Changes in register.blade.php files.

Path : resources/views/auth/register.blade.php

<div class="pakainfo form-group row">
    <label for="role" class="col-md-4 col-form-label">Role</label>
    <div class="col-md-6">
        <select name="role" class="form-control" >
            <option value="superadmin">SuperAdmin</option>
            <option value="manager">Manager</option>
            <option value="member">Member</option>
        </select>
    </div>
</div>

Step 3 : Changes User Model and Controller in Laravel

Customize User Model and Register Controller

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

Step 3.1 Laravel Form validator

Include a simple Laravel validation define a rule for the select box role field:

path : app/Http/Controllers/Auth/RegisterController.php

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:superadmin,manager,member', //custome validate role input
    ]);
}

Step 3.2 Laravel Cerate() Method

Laravel simple make a Cerate() Method in RegisterController

Read Also:  Role based access control using Laravel 5.7 Example

Include role Save or store field to the create() in Controller method:

protected function create(array $data)
{
	return User::create([
		'name' => $data['name'],
		'email' => $data['email'],
		'password' => bcrypt($data['password']),
		'role' => $data['role'],
	]);
}

Step 4 : Customization of the middlewares

I shall make a Laravel middlewares for most of case each of our roles.

Set-up Laravel middlewares

php artisan make:middleware SuperAdmin
php artisan make:middleware Manager
php artisan make:middleware Member

here simple Now, You Can Change this file Like as app/Http/Middleware directory

SuperAdmin.php:

//laravel user roles and permissions in SuperAdmin
use Auth; //at the First

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

Manager.php:

//laravel user roles and permissions in Manager
use Auth; //at the first

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

Member.php:

//laravel user roles and permissions in Member
use Auth; //at the first

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

Step 5: $routeMiddleware(Kernel.php)

Including the Laravel middleware classes to changes $routeMiddleware

Read Also:  Angularjs Store in Localstorage - ngStorage

Path : app/Http/Kernel.php

protected $routeMiddleware = [
    // ...
    'superadmin' => 'App\Http\Middleware\SuperAdmin',
    'manager' => 'App\Http\Middleware\Manager',
    'member' => 'App\Http\Middleware\Member',
];

Step 6 : Set-up Laravel Routes

some changes these Laravel middlewares to routes or to the controller

path : routes/web.php:

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

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

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

specify a Laravel middleware used to dependent in a controller’s constructor,

Use Laravel controller’s constructor

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

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 Laravel Roles Permissions Example Tutorial From Scratch.
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.


Related FAQ

Here are some more FAQ related to this Article:

  1. Read Also:  Reusable AJAX Functions (Post/Get)
  2. Read Also:  PHP Delete All Directory Files In Directory
  3. Read Also:  Angular KeyValue Pipe Example Tutorial
  4. Read Also:  laravel permissions Tutorial with Example
  5. Read Also:  Vuejs set focus Textbox Components
  6. Read Also:  AngularJS z-index property using CSS
  7. Read Also:  Laravel Role based permission ACL Tutorial
  8. Read Also:  how to skip a line in python | python skip lines starting with #
  9. Read Also:  Learn Angular 5 from Scratch - angular 5 Tutorial
  10. Read Also:  Laravel 7 Email Verification Tutorial and Example

Leave a Comment

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