Laravel 9 Role Based Authentication Tutorial

Hello Artisan,

In this Laravel multiple role based authentication in laravel 9 tutorial, I am going to show you step by step that how to create a multiple role based authentication example in Laravel 9. I will simply handle this role based authentication in Laravel 9 using a custom middleware.

So if you still don't know how to handle or how to create a multiple role based authentication, then this example is for you. This role based authentication example will give you a perfect solution for implementing a role based authentication in Laravel 9 application.

So in this laravel 9 role based authentication example, 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 using role based.

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

Let's start with our laravel 9 role-wise authentication example. 

 

Step 1 : Download Laravel Project

As we are going to start from scratch of implementing 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 a 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 the User model as 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 the following the 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 9 Authorization using Gates

 

The 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 controllers AdminController and SuperAdminController to create a user role base login system in laravel.

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

 

Now modify those controllers 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');
    }
}

 

And now update another controller like:

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 the other for super admin.

routes/web.php

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

 

Step 8 : Create Blade File

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

resources/views/admin/home.blade.php

 

And for super admin

resources/views/superadmin/home.blade.php

 

Read also : Laravel 9 Gate and Policy Example From Scratch

 

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

 

#laravel #laravel-9x #acl