Laravel Middleware Basics Explained
Your invoice pages must only be visible to your staff. The simplest way to protect them is to check at the top of every controller method whether the visitor is logged in, and redirect them if not. You write that check in index(), then in show(), then in edit(). After a few weeks the app has 20 methods, and one of them, added late on a Friday, has no check. A customer finds an invoice that was never meant for them.
The same problem appears for other jobs too: logging every request, blocking visitors who send too many requests, or showing a maintenance page. Repeating the same check inside every method does not scale, and one missed copy becomes a security hole.
Middleware solves this by putting the check in one place, in front of your routes. In this lesson you will learn what middleware is, which middleware already runs in your app, and how to apply it to routes.
The Problem with Repeating Checks
Here is what the repeated check looks like in a controller. It uses the session from the last lesson to see if a staff member is logged in:
public function index()
{
if (! session('staff_id')) {
return redirect('/login');
}
return $this->invoiceService->all();
}
public function show(int $invoice)
{
if (! session('staff_id')) {
return redirect('/login');
}
return $this->invoiceService->find($invoice) ?? abort(404);
}
This has the same problems you saw in the lesson on thin controllers:
- The same code is copied into every method, and one missing copy means an unprotected page
- The controller now mixes access rules with its real job
- To change the rule, for example the login address, you must edit every copy
- The check cannot easily be reused for other controllers
What Is Middleware?
Think of the security guard at the gate of an apartment society. Every visitor stops at the gate before reaching any flat. The guard checks who they are, lets some people in and turns others away. The people inside the flats do not need to do any checking, because the gate already did it.
Middleware works like that guard. It is code that sits between the incoming request and your controller. Every request passes through it on the way in, and every response passes through it again on the way out.
Request --> [ Middleware 1 ] --> [ Middleware 2 ] --> Controller Response <-- [ Middleware 1 ] <-- [ Middleware 2 ] <-- Controller
Each middleware can do one of four things:
- Let the request continue to the next step unchanged
- Change the request before passing it on, for example by trimming text values
- Stop the request completely and send a response itself, such as a redirect to the login page
- Change the response on the way back, for example by adding a header
Where Middleware Fits in the Request Lifecycle
In the Request Lifecycle lesson you followed a request from public/index.php to the final response. Middleware is the step between the router and your controller. After Laravel matches a route, it sends the request through the middleware attached to that route, and only then runs the controller.
In modern Laravel (version 11 and later), middleware is configured in bootstrap/app.php. There is no app/Http/Kernel.php file, which older tutorials mention. You will work with bootstrap/app.php in the lessons later in this chapter.
Middleware You Already Use
You have not written any middleware yet, but several pieces already run on every request in your project. Many things you have learned in this chapter work because of them:
TrimStringsandConvertEmptyStringsToNullclean the input, which is why your blank search box gave younullin the Request Object lessonEncryptCookiesencrypts the cookies you set, which is why a cookie created by JavaScript read asnullAddQueuedCookiesToResponseattaches the cookies you added withCookie::queue()StartSessionloads and saves the session, which is whysession()worked in the last two lessonsShareErrorsFromSessionmakes validation errors available to your views, which you will use in the Forms chapterPreventRequestForgerychecks the CSRF token on forms, and it is the source of the419 | Page Expiredpage you have seen mentioned several times. Older tutorials call itVerifyCsrfToken, but Laravel 13 renamed itSubstituteBindingspowers Route Model Binding
Global Middleware and Middleware Groups
Laravel organizes these in two layers. Global middleware runs on every single request, such as the trimming and the maintenance mode check. The web group is a set of middleware that Laravel applies automatically to every route in routes/web.php, and it contains the session, cookie and CSRF pieces from the list above.
This also explains something from the previous lessons. Routes in routes/api.php use the api group, which has no session or cookie middleware. That is why session data and flash messages do not work in API routes.
Every request
Global middleware (trimming, maintenance mode ...)
|
routes/web.php -> web group (cookies, session, CSRF ...)
routes/api.php -> api group (stateless, no session)
|
Middleware you attach to a route or group
|
Controller
You do not need to memorize these lists. The point is that middleware is not a mysterious extra feature. It is how Laravel itself does much of its work.
Applying Middleware to Routes
On top of the defaults, you can attach your own choice of middleware to any route with the middleware() method. The same chaining style you used for ->name() applies.
One Route
Laravel includes some ready-made middleware, and each has a short name called an alias. For example, auth allows only logged-in users:
Route::get('/invoices', [InvoiceController::class, 'index'])
->middleware('auth');
Now every visitor passes through the auth checkpoint before index() runs, and the controller no longer contains any check. The auth middleware needs a login system, which you will build in the Authentication chapter, so do not use it in your project yet. Aliases get their own lesson, Middleware Aliases, Groups & Parameters.
Several Middleware on One Route
Give an array to attach more than one:
Route::get('/invoices', [InvoiceController::class, 'index'])
->middleware(['auth', 'verified']);
A Group of Routes
Repeating ->middleware() on twenty routes brings back the copy-paste problem. Attach it once to a group, as you learned in the Route Groups lesson:
Route::middleware(['auth'])->group(function () {
Route::get('/invoices/summary', InvoiceSummary::class)
->name('invoices.summary');
Route::resource('invoices', InvoiceController::class);
});
Every route inside the group is protected. If you later add a new route inside the group, it is protected automatically, so you cannot forget it.
Excluding Middleware from One Route
Sometimes one route inside a group must stay open, for example a payment callback from Razorpay that cannot log in. Use withoutMiddleware():
Route::middleware(['auth'])->group(function () {
Route::resource('invoices', InvoiceController::class);
Route::post('/payments/razorpay/callback', RazorpayCallback::class)
->withoutMiddleware(['auth']);
});
Trying Middleware Yourself
You can see middleware working right now, without a login system, using the built-in throttle middleware. It limits how many requests a visitor can make. Add it to the summary route:
Route::get('/invoices/summary', InvoiceSummary::class)
->middleware('throttle:3,1')
->name('invoices.summary');
The text after the colon gives the middleware its settings. Here it means 3 requests per 1 minute. The settings after a colon are called parameters, and you will study them in the Middleware Aliases, Groups & Parameters lesson.
Open http://localhost:8000/invoices/summary and refresh it four times quickly. The first three requests work normally. The fourth never reaches your controller, and you see:
429 | Too Many Requests
The middleware stopped the request and sent the response itself. Wait a minute and the page works again. Remove the middleware when you are done testing. Rate limiting is covered fully in the API Versioning & Rate Limiting lesson.
Order Matters
Middleware runs in the order you list it on the way in, and in reverse order on the way out:
->middleware(['first', 'second']) Request --> first --> second --> Controller Response <-- first <-- second <-- Controller
This matters when one check depends on another. For example, a check that needs a logged-in user must run after the one that confirms the user is logged in. A middleware that stops the request ends the journey, and everything after it, including the controller, never runs.
Seeing the Middleware on Your Routes
To see which middleware applies to each route, run the route list command with the verbose option:
php artisan route:list -v
Each route now shows its middleware underneath. Add a second v to expand groups into the individual middleware they contain:
php artisan route:list -vv
This is the quickest way to find out why a route behaves in a certain way, for example why a POST request is rejected with a 419 error.
Before and After Middleware
Middleware can act in two moments. Before the controller, it can inspect or reject the request, such as an auth check or a maintenance mode check. After the controller, it can modify the response, for example by adding a header or recording how long the request took.
The built-in middleware covers many common jobs, but your project will soon need its own, such as a check that only an admin can reach the reports pages. Writing your own middleware is the subject of the next lesson.
What Middleware Should Not Do
Middleware is best for checks and changes that apply to many routes: access, limits, headers and logging. It is not the place for your business logic. Calculating GST or creating an invoice belongs in a service, as you learned earlier. If a middleware starts to look like a small controller, it is doing too much.
Common Mistakes
Mistake 1: Using auth Before There Is a Login System
Route::get('/invoices', [InvoiceController::class, 'index'])->middleware('auth');
The auth middleware sends visitors who are not logged in to a route named login. If your project does not have one yet, you get:
Symfony\Component\Routing\Exception\RouteNotFoundException: Route [login] not defined.
This is expected until you build authentication in Chapter 13.
Mistake 2: A Middleware Name That Does Not Exist
Route::get('/invoices', [InvoiceController::class, 'index'])->middleware('admin');
If admin is not a defined alias, Laravel treats it as a class name and fails with:
Illuminate\Contracts\Container\BindingResolutionException: Target class [admin] does not exist.
Check the spelling. Custom aliases are created in bootstrap/app.php, which you will do in the Middleware Aliases lesson.
Mistake 3: Protecting Some Routes and Forgetting Others
Adding ->middleware('auth') one route at a time makes it easy to miss one. Put related routes in a group, so that new routes inside it are protected automatically. Run php artisan route:list -v to review the result.
Mistake 4: Expecting Sessions in API Routes
Routes in routes/api.php use the api group, which does not start a session. Flash data and session values will not be there on the next request. This is by design, because APIs are stateless.
Mistake 5: Hiding a Link Instead of Protecting the Route
Removing the “Delete” button from the page for ordinary users does not stop anyone from typing the address or sending the request by hand. The check must happen on the server, through middleware or checks inside the controller, because anything in the browser can be changed.
Mistake 6: Putting Heavy Work in Middleware
Global middleware runs on every request, including images and tiny pages. A slow database query or a call to an outside service in the wrong place slows down the whole site. Keep middleware fast and focused.
Quick Summary
- Middleware is code that sits between the request and your controller, and also sees the response on its way back.
- It can let a request through, change it, stop it with its own response, or change the response afterwards.
- Many things already work through middleware: trimming input, cookie encryption, sessions and CSRF protection.
- Laravel 13 calls its CSRF middleware
PreventRequestForgery, which was namedVerifyCsrfTokenin older versions. - Global middleware runs on every request, and the
webandapigroups are applied automatically to their route files. - Attach your own middleware with
->middleware('name')on a route, or on a group withRoute::middleware([...])->group(). - Use
->withoutMiddleware()to leave one route out of a group. - Middleware runs in the listed order on the way in and in reverse order on the way out.
php artisan route:list -vshows the middleware of each route.authneeds a login system, so use it after the Authentication chapter.- Middleware is for checks that apply to many routes, and not for business logic.
What’s Next
You now know how middleware works and how to attach the ready-made ones. But real projects need rules that Laravel does not ship with, such as allowing only admins into the reports section, or blocking access outside business hours. In the next lesson, Creating Custom Middleware, you will write your own middleware class from scratch and attach it to your invoice routes.