Laravel Middleware for Auth Admin Users Roles

Admin Pannel in Laravel 9

Examples of Laravel Middleware for Auth Admin Users Roles. This tutorial shows how to build a sample Laravel middleware for the admin role from scratch. Check if the authenticated user is an admin or a user. If he’s a user, he can’t get admin access to get admin pages.

Middleware provides a convenient mechanism for filtering incoming HTTP requests to your application. Laravel provides authentication middleware that validates that users of your application have been authenticated. Here we use an admin middleware where the user is not an admin and the middleware redirects the user to the dashboard.

However, if the user is an administrator, the middleware allows the request to proceed further to the application. This tutorial will show you step by step how to use middleware in Laravel, or how to call middleware in your controller. Let’s start with the single-role or multi-role Laravel middleware admin role

Laravel 9 Middleware Example Tutorial

Follow the following steps to create Laravel middleware for auth admin and user roles:

  • Step 1 – Install Laravel App
  • Step 2 – Connect Database to App
  • Step 3 – Generate Laravel Authentication
  • Step 4 – Update User’s Migration
  • Step 5 – Create Middleware
  • Step 6 – Admin Protected Middleware Route
  • Step 7 – Create & Update Blade Files
  • Step 8 – Update Controller Methods
  • Step 9 – Multiple Middlewares in Single Route

Step 1: Install Laravel App

First at all, install Laravel 9 using Composer. Open a new command-line interface and run the following command:

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

Go inside the app:

cd laravel-admin

Step 2: Connect Database to App

Now, open your laravel application .env file and make the following database related changes in it.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_admin
DB_USERNAME=root
DB_PASSWORD=

Step 3: Generate Laravel Authentication

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

Open users table migration and update the is_admin field on it.

user_table_migration.php

Step 4: Update User’s Migration

<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->boolean('is_admin')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

After adding the column now run the migration just running the following command.

php artisan migrate

Step 5: Create Middleware

Now Create middleware for handling auth admin roles. Open the terminal and run below command.

php artisan make:middleware IsAdmin

Now you check you have generated a file in your project middleware directory, open and update the below code on it.

app\Http\Middleware\IsAdmin.php

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;

class IsAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (Auth::user() &&  Auth::user()->is_admin == 1) {
             return $next($request);
        }

        return redirect('home')->with('error','You have not admin access');
    }
}

Now open your kernel.php file and go to the protected $routeMiddleware property and update the admin middleware here.

app\Http\Kernel.php

    protected $routeMiddleware = [
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'admin' => \App\Http\Middleware\IsAdmin::class,
    ];

Step 6: Admin Protected Middleware Route

Create routes that an administrator must protect. If the user is not an admin, they will be redirected to the home page. Otherwise, he can visit this page. Now if I want to assign routes to this middleware admin, these routes will be secured and only accessible if the authorized user is an admin. Otherwise, you will be redirected to the home page.

app/routes/web.php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HomeController;
 
 Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('home', [HomeController::class, 'index'])->name('home'); 
Route::group(['middleware' => ['admin']], function () {
   Route::get('admin-home', [HomeController::class, 'adminHome'])->name('admin.home');
});

Step 7: Create & Update Blade Files

Add accessing page link add in the home page which is open after user login.

resources\views\home.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Dashboard</div>

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

                    You are logged in!

                </div>
                <div class="card-body">
                    <div class="panel-body">
                      Check admin view:
                      <a href="{{route('admin.home')}}">Admin Home</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Create a blade file if the user is authenticated with admin then access this page.

resources\views\admin-home.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Admin Home</div>

                <div class="card-body">
                  Welcome to admin dashboard
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Step 8: Update Controller Methods

Now add a method in your controller if a user is authenticated with admin then admin-home function work.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        return view('home');
    }

    public function adminHome()
    {
        return view('admin-home');
    }
}

You can also setup multiple middleware here like this

Route::group(['middleware' => ['auth', 'admin']], function () {
    Route::get('admin-home', [HomeController::class, 'adminHome'])->name('admin.home');
});

About Post Author

Leave a Reply

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