Laravel Middleware acts as a bridge between a request and a response. It is a type of filtering mechanism. Laravel includes a built-in middleware called auth that verifies whether the application user is authenticated.
There are various types of middleware you can use in your application. For example, you can log everything in your application using log middleware.
Various middlewares are included in Laravel, including middleware for authentication and CSRF protection; however, all user-defined middleware is typically located in your application’s app/Http/Middleware directory.
Here are the steps to create a Route Middleware in Laravel 11:
Step 1: Create a Laravel project
composer create-project laravel/laravel LaravelMiddleware --prefer-dist
Go to phpMyAdmin and create one database.
Go inside the LaravelMiddleware project.
cd LaravelMiddleware
Now, configure the database inside the .env file like this:
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=8889 DB_DATABASE=mware DB_USERNAME=root DB_PASSWORD=root
Step 2: Install the laravel/ui package
Type the below command:
composer require laravel/ui
Add the Auth scaffolding using laravel/ui using this command:
php artisan ui bootstrap --auth
After that, you need to install the dependencies using this command:
npm install
Now start the Vite development server using this command:
npm run dev
Step: 3 Adding a field to the users migration file
We need to add one more field inside the users table called “isAdmin.” This field has a boolean value of 1 or 0. If 1, the authenticated user is an admin; otherwise, it is not.
Go to your users’ table migration file and add one more field called isAdmin; its data type is boolean.
public function up(): void { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->boolean('isAdmin')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); });
Run the following command.
php artisan serve
Create a user through the signup form. So go to the following URL: http://localhost:8000/register.
We have not assigned any users to admin, but we can do it manually.
But remember, in a real-time web application, you need to provide an interface to grant administrative rights.
After signing the form, I am just showcasing how you can deal with admin middleware.
For now, assign any user’s isAdmin field to value one manually in the database.
Step 4: Create a Laravel Middleware
Create a middleware in Laravel by typing the following command.
php artisan make:middleware Admin
Navigate to the following file. app >> Http >> Middleware >> Admin.php
You can see Laravel provides some boilerplate.
There is mainly one function you have to deal with, and that is handle().
We need to write the logic in this function to filter the request. If it is satisfied, we should go to the destination page; otherwise, we should go back to login or whatever redirect page you will provide.
I am writing one logic in this function.
/** * Handle an incoming request. * * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next */ public function handle(Request $request, Closure $next): Response { if (Auth::check() && Auth::user()->isAdmin == 1) { return $next($request); } return redirect('home')->with('error','You do not have an admin access'); }
Now, I can use this middleware for any route that I want to protect. For example, if there are some routes that only an admin can access, then I will attach this middleware to that specific route.
Step 5: Attach the admin middleware to the route
Create a route that needs to be admin-protected.
If the user is not an admin, it will redirect to the home page; otherwise, he can access this page.
Modify the routes/web.php file like this:
<?php use Illuminate\Support\Facades\Route; use App\Http\Middleware\Admin; Route::get('/', function () { return view('welcome'); }); Auth::routes(); Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home'); Route::get('/admin/routes', [App\Http\Controllers\HomeController::class, 'admin']) ->name('admin') ->middleware(Admin::class);
In this code, we attached the middleware to the “/admin/routes,” which is now protected; only the admin user can access it.
Add the below code inside the resources/views/home.blade.php file.
@extends('layouts.app') @section('content') <div class="container py-5"> <div class="row justify-content-center"> <div class="col-md-8"> <!-- Dashboard Card --> <div class="card shadow-sm mb-4"> <div class="card-header bg-primary text-white">{{ __('Dashboard') }}</div> <div class="card-body"> <!-- Success Message --> @if (session('status')) <div class="alert alert-success" role="alert"> {{ session('status') }} </div> @endif <!-- Error Message --> @if(\Session::has('error')) <div class="alert alert-danger"> {{\Session::get('error')}} </div> @endif <p class="lead">{{ __('You are logged in!') }}</p> </div> </div> <!-- Admin Card --> <div class="card shadow-sm"> <div class="card-header bg-secondary text-white">{{ __('Admin') }}</div> <div class="card-body"> <a href="{{url('admin/routes')}}" class="btn btn-dark">Admin Panel</a> </div> </div> </div> </div> </div> @endsection @push('styles') <style> .container { max-width: 960px; } .card-header { font-size: 1.25rem; font-weight: bold; } .btn-dark { width: 100%; text-align: center; } </style> @endpush
Now, the remaining thing is to add an admin() function inside the app/Http/ControllersHomeController.php file like this:
<?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 admin() { return view('admin'); } }
Step 6: Create an admin.blade.php file
Create one view called admin.blade.php in the views folder.
@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"> <p>This is admin page</p> </div> </div> </div> </div> </div> @endsection
Go to the login page and try to log in.
Here is my login page for Laravel.
After logging in, this is how my screen looks like this.
You are logged in as an admin, so; you can see the following page.
Since I am not an admin user, if I try to access the Admin Panel, it will give me an error like this:
Now, if we want to access an admin panel, we need to go to the mysql database and change the value of isAdmin from NULL to 1 like this:
Now, go to this URL: http://localhost:8000/admin/routes
Now you will be access this route because we are logged in as an administrator:
Registering Middleware Globally
If your application has a requirement to run a middleware on every HTTP request to your application, you may append it to the global middleware stack in your application’s bootstrap/app.php file:
<?php use Illuminate\Foundation\Application; use Illuminate\Foundation\Configuration\Exceptions; use Illuminate\Foundation\Configuration\Middleware; use App\Http\Middleware\Admin; return Application::configure(basePath: dirname(__DIR__)) ->withRouting( web: __DIR__ . '/../routes/web.php', commands: __DIR__ . '/../routes/console.php', health: '/up', ) ->withMiddleware(function (Middleware $middleware) { $middleware->append(Admin::class); }) ->withExceptions(function (Exceptions $exceptions) { // })->create();
In this file, check this code specifically:
->withMiddleware(function (Middleware $middleware) { $middleware->append(Admin::class); })
Here, we are appending “Admin middleware” globally to the Laravel application. Now, it will run for every request incoming to our project.
The append() method adds the middleware to the end of the list of global middleware.
If you would like to add middleware to the beginning of the list, you should use the prepend() method.
That’s all!
Sujan
really helpful. really, really helpful.
ajid
Tx for the artical, but how to make login if the user isadmin==1 redirect to view(admin) not to view(home). tx b
Sasindu Rathnayake
Greate.you saved lot’s my time. thank you.i hope you make continue this.
Andy
Oh my good, this is so super awesome tutorial. I finally understand middlewares!!!
bhola khawas
Thanks for the post really helped me..
Gurpreet kait
Thanks for the valuable content, I have seen the post before I was writing it on my end. Please give a review if possible. Thanks.