Last updated on October 18, 2026
Understanding Laravel Middleware for Application Security

January 8, 2024 · 6 min read

This lesson is part of our free Laravel tutorial for beginners. The code examples use Laravel 13.
What is Laravel Middleware?
Laravel middleware is like the security team for your application. They check the credentials of incoming HTTP requests and decide whether to let them through to your application, hold them for further inspection, or turn them away.
It’s a layer that sits between the request and the response. You can use middleware for a variety of tasks, such as authenticating users, logging requests, or even modifying the request before it reaches your application logic.
How the Middleware Works
When a request enters your Laravel application, it goes through a stack of middleware before reaching the route that handles it. After the route’s controller does its work, the response generated by the controller also goes through the middleware stack before it’s sent back to the user.
Default Laravel Middleware: Web and API
Laravel comes with a set of default middleware that is essential for web and API routes. To use these default middleware, you don’t need to register them manually as they are already set up but you are allowed to customize them if needed.
The web middleware group is automatically applied to your routes/web.php file and includes middleware such as EncryptCookies, AddQueuedCookiesToResponse, StartSession, ShareErrorsFromSession, PreventRequestForgery (the CSRF protection middleware, called VerifyCsrfToken in older versions), and SubstituteBindings. These middleware are responsible for maintaining the state of the web application, handling sessions, CSRF protection, and more.
On the other hand, the API middleware group is applied to your routes/api.php file. A new Laravel 13 app does not have this file until you run php artisan install:api. In Laravel 13, the api group only contains SubstituteBindings. It does not limit requests by default, so add the throttle middleware to your API routes yourself, for example ->middleware('throttle:60,1') for 60 requests per minute. Rate limits prevent abuse and overloading of your server.
You do not add the web group to your routes yourself. Laravel applies it to every route in routes/web.php. If you want to add your own middleware to the group, use the web method in the bootstrap/app.php file:
use App\Http\Middleware\LogRequests;
->withMiddleware(function (Middleware $middleware): void {
// Run LogRequests on every route in routes/web.php
$middleware->web(append: [
LogRequests::class,
]);
})In the example above, every route in routes/web.php runs the default web middleware first, then LogRequests. Routes in routes/api.php do not get the web group, which means they do not have session state or CSRF protection.
Creating a Laravel Middleware
To create a new middleware in Laravel, you can use the Artisan command-line tool:
php artisan make:middleware CheckAuthorStatus
This command generates a new middleware class named CheckAuthorStatus in the app/Http/Middleware directory.
Middleware Example
Let’s say we want to create a middleware that checks if the authenticated user is an author before allowing them to create a new blog post.
Here’s what our CheckAuthorStatus middleware might look like:
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class CheckAuthorStatus
{
public function handle(Request $request, Closure $next)
{
if (Auth::check() && Auth::user()->is_author) {
return $next($request);
}
return redirect('/')->with('error', 'Only authors can create a post.');
}
}In this middleware, we’re checking if the user is authenticated and if they have an is_author property set to true. If they’re not an author, we redirect them to the home page with an error message.
For this to work, we need to modify our user migration and add a new column that will modify the state of a user to an author. Since our app is not live yet, we can go ahead and make the change in the migration directly:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
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->string('password');
$table->boolean('is_author')->default(false);
$table->rememberToken();
$table->timestamps();
});
// ...the password_reset_tokens and sessions tables stay as they are
}
public function down(): void
{
Schema::dropIfExists('users');
}
};We will save it as a boolean value where the default value is false. Then we can run the following command to refresh the migrations that we had before and run our seeders again:
php artisan migrate:fresh --seed
If the site is live, DO NOT RUN that command because it will delete all the previous data. We need to create a new migration script that will only modify the user migration:
php artisan make:migration add_is_author_to_users_table --table=users
Next, you would update the migration file to include the new column:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->boolean('is_author')->default(false);
});
}
public function down(): void
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('is_author');
});
}
};After creating the migration, run the migration command to update the database without any seeders:
php artisan migrate
Now, your users table has an is_author boolean column that you can use to determine if a user is an author.
Registering the Middleware
After creating middleware, you need to register it in your application before it can be used. Middleware can be registered globally, assigned to routes, or grouped within route groups.
To register middleware, add it to the withMiddleware() array in the bootstrap/app.php file:
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
$middleware->alias([
'checkAuthorStatus' => \App\Http\Middleware\CheckAuthorStatus::class,
]);
})
->withExceptions(function (Exceptions $exceptions): void {
//
})->create();Now, you can use the checkAuthorStatus middleware in your routes.
Using Middleware in Routes
With our CheckAuthorStatus middleware registered, we can use it in our routes file to protect the route that creates new blog posts:
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
Route::get('/posts/create', [PostController::class, 'create'])
->middleware('checkAuthorStatus');Now, only users who are authors can access the form to create a new blog post.
Applying Middleware with Attributes in Laravel 13
Laravel 13 lets you apply middleware directly to a controller class or method with the #[Middleware] PHP attribute, instead of chaining ->middleware() in the route definition:
use App\Http\Middleware\CheckAuthorStatus;
use Illuminate\Routing\Attributes\Controllers\Middleware;
#[Middleware(CheckAuthorStatus::class, only: ['create', 'store'])]
class PostController extends Controller
{
// controller methods...
}This keeps middleware concerns co-located with the controller rather than scattered across route files. On Laravel 11 and 12, you get the same result when the controller implements the HasMiddleware interface and returns new Middleware(CheckAuthorStatus::class, only: ['create', 'store']) from a static middleware() method. Both approaches work in Laravel 13, so use whichever fits your project structure.
Middleware Parameters
Middleware can also receive additional parameters. For example, you might want to have a middleware that checks if a user has a specific role:
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class CheckUserRole
{
public function handle(Request $request, Closure $next, $role)
{
if (Auth::check() && Auth::user()->role === $role) {
return $next($request);
}
return redirect('/')->with('error', "You do not have access here.");
}
}You can pass the $role parameter to the middleware in your route definition like so:
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AdminController;
Route::get('/admin', [AdminController::class, 'index'])
->middleware('role:admin');To make this work, you need to register the middleware just as we did for the CheckAuthorStatus middleware.
However, in this case, you need to do the following:
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
$middleware->alias([
'checkAuthorStatus' => \App\Http\Middleware\CheckAuthorStatus::class,
'role' => \App\Http\Middleware\CheckUserRole::class,
]);
})
->withExceptions(function (Exceptions $exceptions): void {
//
})->create();
Conclusion
Middleware in Laravel serves as the guardian of your application, ensuring that only valid requests are processed by your routes and controllers. They are incredibly flexible and powerful tools for managing HTTP requests and responses. By using middleware, you can add layers of protection, handle authentication, perform logging, and more, keeping your blog secure and running smoothly. As you become more familiar with Laravel middleware, you’ll discover even more ways to enhance the functionality and security of your blog application.
More Lessons in the Series
This article is part of our series Laravel for Beginners: A Step-by-Step Guide to Learn the Concepts.
Bring Your Ideas to Life 🚀
If you need help with a Laravel project let’s get in touch.
Lucky Media is proud to be recognized as a leading Laravel Development Agency
Technologies

Stay up-to-date
Be updated with all news, products and tips we share!
