Laravel 7.x Role Based Authentication Tutorial

Hello Artisan

In this laravel user role based authentication tutorial i will discuss from scratch about role based authentication and access control in Laravel. In this Laravel 7 role based authentication example, i will show how we can make different admin panel for admin and super admin.

In this role wise authentication laravel, you can learn how you can create middleware to control user access. Sometimes we need to create admin panel for multiple users. That time we need to create role based authentication or login system in laravel. 

We can create role based authorization using Laravel gate. But in this tutorial i am not going to use Laravel gate. I will simply create a user table and a user_roles table along with a roles table. So in this example you will learn also laravel multiple user authentication.

Let's start our laravel authorization example. 

 

Read also : Laravel 7.x User Roles and Permissions Tutorial

 

Preview of Laravel roled base authorization tutorial

user-role-based-login-system-in-laravel

 

Step 1 : Download Laravel Project

As we are going to start from scratch of implement permissions laravel tutorial, so download a fresh laravel project to create laravel authorization.

composer create-project --prefer-dist laravel/laravel blog

 

Step 2:  Make Auth

In this laravel authorization tutorial we need to create auth first. So create it.

composer require laravel/ui --dev
php artisan ui vue --auth
npm install
npm run watch

 

Step 3 : Make Model

We need role model and user_roles table. so create it by the following command.

php artisan make:model Role -m
php artisan make:migration create_role_user_table

 

Now paste this below code

database/migration/create_roles_table.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');
    }
}

 

database/migration/create_roles_user_table.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');
    }
}

 

Step 4 : Modify User Model

In this step we need to modify User model as like below.

App\User.php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

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

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

    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;
    }
}

 

Step 5 : Create Middleware

In this step we have to create middleware to control user access. So create middleware by following command.

php artisan make:middleware CheckRole

 

Now open check role middleware and paste this below code

App\Http\Middleware\CheckRole.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);
    }
}

 

Read also : Laravel 7.x Authorization using Gates

 

Next step is to register the middleware we just created. Open Kernal.php which is located in $routeMiddleware to include the role middleware.

App\Http\Kernel.php

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

 

Step 6 : Create Controller

Let’s create two new controller’s AdminController and SuperAdminController to create user role base login system in laravel.

php artisan make:controller AdminController
php artisan make:controller SuperAdminController

 

Now modify thos controller by the following code

App\Http\Controllers\AdminController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

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

    public function index()
    {
        return view('admin.home');
    }
}

 

App\Http\Controllers\SuperAdminController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

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

    public function index()
    {
        return view('superadmin.home');
    }
}

 

 

Step 7 : Create Routes

In this step we need to create two routes. one for admin and other for super admin.

routes/web.php

Route::get('/admin', '[email protected]');
Route::get('/superadmin', '[email protected]')

 

Step 8 : Create Blade File

Almost all are set to. Let’s  now we need to build home page views for both admin and superadmin sections of the application. 

resources/views/admin/home.blade.php

 

And for super admin

resources/views/superadmin/home.blade.php

 

Read also : Laravel 7.x Gate and Policy Example From Scratch

 

Now you can check it. Hope this Laravel 7 role based authentication tutorial will help you.