Laravel 10 Middleware Tutorial With Example

Last updated on May 23, 2023

Middleware allows you to perform an action between request and response. It is Laravel’s component that has the ability to filter the request.

To understand more, let’s assume you don’t want to allow users to register in your application who are under 18 years old or you can simply call it adult verification. To implement this feature you need a Middleware that will enable users to register after checking their age in the incoming request.

Syntax:

You can create Middleware in your Laravel application through the below command,

php artisan make:middleware YourMiddlewareName

The above command creates middleware in your Laravel application, so you just need to replace YourMiddlewareName with the middleware name that you want to add.

Types of Middleware in Laravel

In the Laravel framework, there are three kinds of middleware,

  1. Global Middleware
  2. Route Middleware

Global Middleware

Laravel framework runs global middleware on every HTTP incoming request that enters the application.

Route Middleware

Laravel framework allows you to assign middleware to any route. Also, you can assign multiple middlewares to single or multiple routes.

Create Custom Middleware in Laravel

In this tutorial, we will be creating a custom middleware that will check the user’s age and then allow them to register or reject. So before going into detail you need to install a fresh Laravel application in case you didn’t install it yet.

Install Fresh Laravel along with Authentication

Let me give you a quick overview of the Laravel version that I am using for this tutorial is 10.5.1 and I used the below commands for installing it.

Below is composer command, I used for Installing the Laravel application in terminal

laravel new coder-advise

Then I installed the Laravel breeze package by the below composer command that creates authentication views, routes, and controllers for the Laravel application.

composer require laravel/breeze --dev

Once the composer installed the breeze package then install it through the below command.

php artisan breeze:install

It will ask you a few questions about stack, dark mode support, and Pest test. In my case, I selected blade for the stack, no for dark mode, and no for the Pest test. In last you need to run the below command to create tables in the database.

php artisan migrate

After running the migration the authentication module will be fully installed in Laravel and ready to use for sign-up and sign-in. Now let’s get back to the topic.

Create Middleware Through Command

We need to create a middleware with the name VerifyAge. Run the below command.

php artisan make:middleware VerifyAge

It will create a middleware class inside app/Http/Middleware directory. Next, add the below if-statement in the handle() method that will check the user’s age and act accordingly.

if ($request->age < 18) {
     return Redirect::back()->withErrors(['age' => 'Sorry you are not allowed to register.']);
}

The above statement will redirect back the user with an error message if the age is less than 18. Also, import the Redirect class into the middleware through the below code

use Redirect;

Next, we need to register the VerifyAge middleware into the middleware aliases. Middleware aliases are located in Kernel.php.

To register the middleware into middleware aliases, go to app/Http/ directory and open Kernel.php. Then add your middleware along with the alias and path of middleware as an item in the $middlewareAliases array.

protected $middlewareAliases = [
        'verify.age' => \App\Http\Middleware\VerifyAge::class,
];

We registered middleware with verify.age alias. Next, we need the user’s age which we can get through his birthday which is a better way I guess. But in this article, we are going with the simplest way by keeping Age input where the user will be putting the age.

So go to resources/views/auth directory and open register.blade.php. In this blade, file add the below HTML for age input under the confirmed password’s input.

<!-- Verify Age -->
<div class="mt-4">
    <x-input-label for="age" :value="__('Age')" />
    <x-text-input id="age" class="block mt-1 w-full" type="number" name="age" :value="old('age')" required />
    <x-input-error :messages="$errors->get('age')" class="mt-2" />
</div>

After adding the above HTML code, your registration form should look as below.

Add Middleware to Route

Once the age input is added, you need to add VerifyAge middleware to the store route which is inside auth.php. So go to the routes directory and open auth.php. Find the register route with the store method from RegisteredUserController class and add VerifyAge middleware to it or simply replace it with the below code,

Route::post('register', [RegisteredUserController::class, 'store'])->middleware('verify.age');

Now, we need to test if the middleware works in the right way. So run the Laravel application and click on register. I tested by putting age 17 and got an error message that displays in the form.


Written by
I am a skilled full-stack developer with extensive experience in creating and deploying large and small-scale applications. My expertise spans front-end and back-end technologies, along with database management and server-side programming.

Share on:

Related Posts

Tags: Laravel,