Middleware in Laravel 11

laravel 11 middleware
12 May 2025

Introduction to Middleware in Laravel


Hello friends! Today we want to talk about Middleware in Laravel 11. When we discuss Middleware, we are actually talking about a layer that can manage the request to the controller before or after executing a specific action.


In other words, Middleware is very useful for managing requests. For example, we can use Middleware to check if a user is logged in or not, or whether the user has permission to access a specific page. This increases the security of our application significantly.


Also, Middleware can be used for other purposes like logging, or even timestamping requests. In Laravel, by default, we have several Middleware such as auth, guest, and verified that manage user statuses.


So let’s take a look at how to create a new Middleware in Laravel and how to utilize it effectively. This task is quite simple and we can accomplish this with just a few lines of code.



Creating a New Middleware


To create a new Middleware, start with the command line and run the following command:


php artisan make:middleware CheckAge

This command will create a new file named CheckAge.php in the app/Http/Middleware directory. Now let’s take a look at this file.



Middleware Code



<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class CheckAge
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param int $age
* @return mixed
*/
public function handle($request, Closure $next, $age)
{
if (Auth::check() && Auth::user()->age < $age) {
return redirect('home');
}

return $next($request);
}
}


Explanation of Middleware Code


Code 1:

namespace App\Http\Middleware;
This line specifies where this code is located. We are currently working within the namespace called Middleware in Laravel.

Code 2:

use Closure;
Here we are using the Closure class to manage the requests.

Code 3:

public function handle($request, Closure $next, $age)
This function handles the request. If the user's age is less than the specified amount, they will be redirected to the home page.

Code 4:

return $next($request);
If the user meets the required conditions, this line allows the request to proceed to the next controller for processing.

FAQ

?

What does Middleware in Laravel do?

?

How can I create Middleware?

?

Can I use multiple Middleware at the same time?