LaravelLaravel18 min read

Middleware: Filtering Requests Before Controllers

Understand how middleware works and how to create custom middleware for authentication, roles, and logging.

Rachel Thompson
November 10, 2025
4.1k128

Middleware allows you to run logic before or after a request reaches your controller.

  Common use cases:
  - Check if user is logged in
  - Verify roles or permissions
  - Log requests
  - Add headers
  
  ## Built-in example
  
  ```php
  Route::get('/dashboard', function () {
    return view('dashboard');
  })->middleware('auth');
  ```
  
  ## Create custom middleware
  
  ```bash
  php artisan make:middleware IsAdmin
  ```
  
  ```php
  public function handle($request, Closure $next) {
    if (!auth()->user()?->is_admin) {
      abort(403);
    }
    return $next($request);
  }
  ```
  
  ## Middleware flow
  
  ```mermaid
  flowchart LR
    A[Request] --> B[Middleware]
    B --> C[Controller]
    C --> D[Response]
    D --> B
  ```
  
  Middleware keeps your controllers focused on business logic.
  
  In the next tutorial, we will decouple logic using events and listeners.
#Laravel#Middleware#Advanced