Laravel Middleware
Middleware is code that runs before a request reaches a route. It can stop the request or pass it on.
A route without middleware
A plain route answers every request.
Route::get('/l42/open', function () {
return 'Open page';
});A guarded route
With the token, the page opens.
Route::get('/l42/guarded', function () {
return 'Secret page';
})->middleware(CheckToken::class);A route that adds a header
Middleware can also change the response on the way out.
Route::get('/l42/stamped', function () {
return 'Stamped page';
})->middleware(AddStamp::class);Example
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Symfony\Component\HttpFoundation\Response;
class CheckToken
{
public function handle(Request $request, Closure $next): Response
{
if ($request->query('token') !== 'letmein') {
return response('Blocked', 403);
}
return $next($request);
}
}
Route::get('/l42/guarded', function () {
return 'Secret page';
})->middleware(CheckToken::class);Key points
- Middleware: code that runs before a route handles a request.
- Use middleware to check a condition on every request to a route.
- Use the next step to pass the request on to the route.
- Use a middleware class to keep the check in one place.
In this example, the handle method reads the token from the address. A missing or wrong token returns a Blocked response. A right token calls the next step, and the route returns the secret page. Middleware is code that runs before a request reaches a route. Open /l42/guarded?token=letmein in the browser to see the output.
Note
Middleware runs in the order it is listed.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What happens when middleware does not call the next step?