Laravel Middleware Tutorial for Auth Admin Users Roles

Laravel middleware for auth admin users example, In this tutorial we will learn how to create laravel middleware for admin roles example from scratch. We will check is auth user is admin or user, If he is user then we din’t get any admin access for getting the admin pages.

Middleware provide a convenient mechanism for filtering HTTP requests entering your application. Laravel provide us auth middleware that verifies the user of your application is authenticated. Here we use Admin middleware where the user is not an admin, then middleware will redirect the user to back to dashboard.

However, if the user is Admin, the middleware will allow the request to proceed further into the application. This tutorial gives you step by step easy way laravel middleware example Tutorial for Auth Admin Users from scratch and how to use middleware in laravel or how to call middleware at controller. let’s start for laravel middleware admin roles for single or multiples…

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 – Update Users Migration
  • Step 4 – Generate Laravel Authentication
  • 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 10 – Generate Dummy Data with Admin & User Roles Testing

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-middleware

Go inside the app:

cd laravel-middleware

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_middleware
DB_USERNAME=root
DB_PASSWORD=

Step 3: Update Users Migration

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

Or you can Add a new column to existing table in a migration.

database\migrations\2014_10_12_000000_create_users_table.php

<?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 4: Generate Laravel Authentication

Run the laravel authentication command for using laravel middleware for users admin roles.

In laravel 5 or below:

php artisan make:auth

In laravel 6+ version:

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

Step 5: Create Middleware

Now Create middleware for handle auth admin roles. Open the command prompt and run bellow command.

php artisan make:middleware IsAdmin

Now you check you have generate file in your project middleware directory, open and update 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 you kernel.php file and go to protected $routeMiddleware property and update the admin middleware here.

app\Http\Kernel.php

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    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 one route, which needs to be admin protected, and if the user is not an admin, then it will redirect to the home page; otherwise, he can access this page. Now, if we want to assign any route to this middleware admin, then these routes now protected and only accessible when an authorized user is admin; otherwise, it will redirect to the homepage.

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-view', [HomeController::class, 'adminView'])->name('admin.view');
});

Step 7: Create & Update Blade Files

Add accessing page link add in home page which is open after use 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.view')}}">Admin View</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-view.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 View</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 is user is authenticated with admin then adminView 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 adminView()
    {
        return view('admin-view');
    }
}

You can add multiple middlewares with the group routes in laravel just like below.

Step 9: Multiple Middlewares in Single Route

Route::group(['middleware' => ['auth', 'admin']], function () {
    Route::get('admin-view', 'HomeController@adminView')->name('admin.view');
});

Step 10: Generate Dummy Data with Admin & User Roles Testing

Now create a laravel users table seeder and add some data in your users table. You can manually register and update in your users table is_admin column to adding 1 or making null just checking the middleware funcationality.

Create the seeder just running the following command

php artisan make:seeder UsersSeeder

database/seeds/UsersSeeder.php

<?php 
use Illuminate\Database\Seeder; 
use App\User; class UsersSeeder extends Seeder { 
    /** 
    * Run the database seeds. 
    * 
    * @return void */

 
   public function run() { 
           User::truncate(); 
           $users = [ 
            [ 
              'name' => 'Admin',
              'email' => 'admin@gmail.com',
              'password' => '123456',
              'is_admin' => '1',
            ],
            [
              'name' => 'User',
              'email' => 'user@gmail.com',
              'password' => '13456',
              'is_admin' => null,
            ],
             [
              'name' => 'Client',
              'email' => 'client@gmail.com',
              'password' => '13456',
              'is_admin' => null,
            ] 
          ];

          foreach($users as $user)
          {
              User::create([
               'name' => $user['name'],
               'email' => $user['email'],
               'password' => Hash::make($user['password'])
             ]);
           }

    }
}

After adding code in users table seeder run below command

php artisan db:seed --class=UsersSeeder

Learn: How to Create Database Seeder in Laravel Example

Now you can check Laravel Middleware Tutorial for Auth Admin Users just login with admin@gmail.com or user@gmail.com/

If you are login using admin@gmail.com then you can access the admin view access and if you are login using user@gmail.com then you could’nt access the admin dashboard section.

So, Friends the Laravel Middleware Tutorial for Auth Admin Users with roles bases is over now. If you have any questions please comment below, we are happy to help you. Follow us on twitter for more updates.

7 thoughts on “Laravel Middleware Tutorial for Auth Admin Users Roles”

Leave a Comment