🔐 How to Use and Create Middleware in Laravel 12

Middleware in Laravel acts as a bridge between a request and a response. It allows you to perform filtering, validation, modification, and redirection logic before or after the request hits your application logic.

In this blog post, we’ll explain what middleware is, how to use built-in middleware, how to create your own, and how to register and apply middleware in Laravel 12 — step by step.


📌 What is Middleware in Laravel?

Middleware are like filters for HTTP requests. They allow you to:

  • Check authentication
  • Log request data
  • Apply rate limiting
  • Modify headers
  • Redirect unauthenticated users
  • Block requests under certain conditions

For example, you can block users under 18 years old or redirect unauthenticated users to the login page.


🧰 Step 1: Use Built-In Middleware

Laravel provides many built-in middleware such as:

Middleware Purpose
auth Ensures the user is authenticated
guest Ensures the user is a guest
verified Ensures email verification
throttle Limits request rate (e.g. APIs)
csrf Protects against CSRF attacks

Example: Apply Auth Middleware to a Route
Route::get('/dashboard', function () { return 'Welcome to Dashboard'; })->middleware('auth');

This route is accessible only if the user is authenticated.


✨ Step 2: Create Custom Middleware

To create your own middleware, use the Artisan command:

php artisan make:middleware CheckAge

This creates a new file at:

app/Http/Middleware/CheckAge.php

📝 Step 3: Write Logic in Middleware

Open the newly created file and add your custom logic. Here’s how you might block users under age 18:

namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; class CheckAge { public function handle(Request $request, Closure $next) { if ($request->age < 18) { return response('Access Denied. You must be 18 or older.'); } return $next($request); // Proceed to controller } }

🗂️ Step 4: Register Middleware

Laravel 12 removes Kernel.php and replaces it with ->withMiddleware() registration in bootstrap/app.php.

Locate this section in bootstrap/app.php:

->withMiddleware(function (Middleware $middleware) {
... });

➕ Add your custom middleware as an alias:


->withMiddleware(function (Middleware $middleware) { $middleware->alias([ 'check.age' => \App\Http\Middleware\CheckAge::class, // other aliases... ]); $middleware->web(append: [ \App\Http\Middleware\CheckAge::class, // optional global middleware ]); $middleware->redirectGuestsTo(fn(Request $request) => route('login')); });

🚦 Step 5: Use Middleware in Routes

Once registered, you can use it in your routes like this:

Route::get('/restricted', function () { return 'You are old enough to access this page.'; })->middleware('check.age');

Now test it by visiting:

http://localhost:8000/restricted?age=17

You’ll see:

Access Denied. You must be 18 or older.

Try it with ?age=25 to pass the filter.


🔁 Step 6: Middleware in Controllers

You can also use middleware inside controllers:

class ProfileController extends Controller { public function __construct() { $this->middleware('auth'); } public function index() { return view('profile'); } }

You can even apply it to specific methods:

$this->middleware('auth')->only(['edit', 'update']); $this->middleware('guest')->except(['logout']);

🧪 Step 7: Middleware with Parameters

Some middleware accept parameters. For example, Laravel’s built-in throttle middleware allows you to limit API usage:

Route::middleware('throttle:5,1')->get('/api/data', function () { return 'You can access this 5 times per minute.'; });

🚀 Step 8: Route Group Middleware

You can apply middleware to multiple routes using groups:

Route::middleware(['auth', 'verified'])->group(function () { Route::get('/dashboard', function () { return 'Dashboard'; }); Route::get('/account', function () { return 'Account Settings'; }); });

This applies both auth and verified middleware to all routes inside the group.


📈 Step 9: Middleware Execution Order

  • Global middleware is defined in the $middleware array of Kernel.php and applies to all routes.
  • Route middleware is assigned to specific routes or controllers via the middleware() method.
  • Middleware runs in the order it’s defined in the array.


✅ Summary: Key Takeaways

Task Command or File
Create middleware php artisan make:middleware Name
Write logic app/Http/Middleware/Name.php
Register route middleware Kernel.php → $routeMiddleware
Use middleware in routes Route::get()->middleware()
Use middleware in controller $this->middleware('name')
Use parameters in middleware middleware('throttle:5,1')

Post a Comment

Previous Post Next Post

Contact Form