What is Middleware

Middleware is a software layer or component that acts as a bridge between different applications, systems, or services, enabling them to communicate and interact effectively. It operates in the middle of a software stack, handling tasks such as data translation, request routing, authentication, and message passing. Middleware is commonly used in distributed systems, web applications, and enterprise software environments.

Key Features of Middleware

  1. Integration: Connects different software components or applications, often written in different programming languages or running on different platforms.
  2. Abstraction: Provides a uniform interface, abstracting away the complexities of underlying systems or protocols.
  3. Scalability: Enables systems to scale by managing interactions between components efficiently.
  4. Security: Often handles authentication, authorization, and data encryption to ensure secure communication.
  5. Message Queuing: Manages asynchronous communication by queuing messages between systems or services.
  6. Logging and Monitoring: Tracks requests, responses, and performance metrics to ensure system reliability.

Common Types of Middleware

  • Application Middleware: Bridges applications with underlying resources, like databases or other services (e.g., API gateways).
  • Message-Oriented Middleware (MOM): Facilitates communication between distributed systems using messages (e.g., RabbitMQ, Apache Kafka).
  • Database Middleware: Simplifies interactions with databases by abstracting database calls (e.g., ORM libraries like Hibernate or Sequelize).
  • Web Middleware: Manages HTTP requests and responses in web frameworks (e.g., middleware in Express.js, Django, or Flask).

Middleware in Action

For example, in a web application, middleware in a server framework (e.g., Express.js) might:

  1. Log all incoming requests.
  2. Check user authentication and permissions.
  3. Parse JSON in the request body.
  4. Route the request to the appropriate handler.

Middleware makes complex software systems more modular, maintainable, and scalable by handling common functionality in a centralized way.


Middleware in Laravel

In Laravel, middleware provides a mechanism to filter HTTP requests entering your application. It acts as a bridge between the incoming request and the application logic. Middleware can be used for tasks like authentication, logging, request modification, or CORS handling. Here’s how middleware works in Laravel:


1. Middleware Workflow in Laravel

  • Incoming Request: When a client sends an HTTP request, Laravel routes the request through middleware before it reaches the controller.
  • Middleware Execution: Middleware inspects, processes, or modifies the request. It can:
    • Allow the request to proceed to the next middleware or the controller.
    • Modify the request or response.
    • Halt further processing (e.g., if the user is not authenticated).
  • Outgoing Response: Once the controller handles the request and generates a response, middleware can also modify the response before it’s sent to the client.

2. Creating Middleware in Laravel

You can create a middleware using the artisan command:

php artisan make:middleware CheckAge

This creates a file in the app/Http/Middleware directory.


3. Structure of Middleware

A middleware class typically looks like this:

<?php  
namespace App\Http\Middleware;  
use Closure; 
use Illuminate\Http\Request;  
class CheckAge {     
    /**
     * 
     * Handle an incoming request.
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     *  @return mixed
     */

    public function handle(Request $request, Closure $next)     
    {
        // Check the condition
        if ($request->age < 18) {
            return response('Access denied. You must be 18 years or older.', 403);
        }

        // Proceed to the next middleware or controller
        return $next($request);
    }
}
  • $request: The incoming HTTP request.
  • $next: A callback to pass the request to the next middleware or controller.

4. Registering Middleware

Middleware must be registered to take effect. You can register middleware in two ways:

a. Global Middleware

Middleware that applies to all routes. Add it to the $middleware array in app/Http/Kernel.php.

protected $middleware = [
    \App\Http\Middleware\CheckAge::class,
];

b. Route Middleware

Middleware applied to specific routes. Add it to the $routeMiddleware array in app/Http/Kernel.php.

protected $routeMiddleware = [
    'check.age' => \App\Http\Middleware\CheckAge::class,
];

You can then apply it to routes like this:

Route::get('/profile', function () {

    // Your controller logic 

})->middleware('check.age');

5. Middleware Groups

You can group multiple middleware and apply them together. Middleware groups are defined in app/Http/Kernel.php. For example:

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // Add your custom middleware here
    ],
];

Apply the group to routes:

Route::middleware(['web'])->group(function () {
    Route::get('/', function () {
        return view('welcome');
    }); 
});

6. Common Use Cases

  • Authentication: Ensure users are logged in before accessing certain routes.
  • CORS (Cross-Origin Resource Sharing): Set headers for API responses.
  • Rate Limiting: Limit the number of requests from a client.
  • Custom Logic: Implement application-specific rules like checking user roles.

Middleware is an essential part of Laravel’s request lifecycle, providing a clean and modular way to handle pre- and post-request logic.


List of pre-defined middleware in laravel

Laravel comes with several predefined middleware that handle common functionalities. These middleware are included in the framework and registered in the app/Http/Kernel.php file under either the $middleware, $middlewareGroups, or $routeMiddleware properties. Here’s a list of predefined middleware and their purposes.


1. Global Middleware

These middleware are applied to all HTTP requests. They are listed in the $middleware array of the Kernel class.

  • \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode

    • Checks if the application is in maintenance mode and blocks access if it is.
  • \Illuminate\Foundation\Http\Middleware\ValidatePostSize

    • Validates that the incoming request does not exceed the maximum post size defined in the post_max_size setting.
  • \App\Http\Middleware\TrimStrings

    • Automatically trims whitespace from request input data.
  • \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull

    • Converts empty strings in request input data to null.
  • \App\Http\Middleware\TrustProxies

    • Handles trusted proxies for determining the client’s IP address and protocol.

2. Middleware Groups

Middleware groups allow you to apply multiple middleware to specific routes or groups of routes. The two default middleware groups in Laravel are web and api.

a. Web Middleware Group

Found in $middlewareGroups['web'], these are used for routes that require session and state management (e.g., web pages).

  • \App\Http\Middleware\EncryptCookies

    • Encrypts cookies before they are sent to the client.
  • \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse

    • Adds cookies to the response that were queued during the request.
  • \Illuminate\Session\Middleware\StartSession

    • Starts the session for the request.
  • \Illuminate\View\Middleware\ShareErrorsFromSession

    • Shares validation errors from the session with views.
  • \App\Http\Middleware\VerifyCsrfToken

    • Protects against Cross-Site Request Forgery (CSRF) attacks.
  • \Illuminate\Routing\Middleware\SubstituteBindings

    • Resolves route model bindings and injects the models into the route.

b. API Middleware Group

Found in $middlewareGroups['api'], these are used for stateless API routes.

  • \Illuminate\Routing\Middleware\ThrottleRequests

    • Limits the number of requests to prevent abuse or denial-of-service attacks.
  • \Illuminate\Routing\Middleware\SubstituteBindings

    • Resolves route model bindings and injects the models into the route.

3. Route Middleware

These middleware are registered in the $routeMiddleware array and can be applied to individual routes or route groups.

  • auth (\App\Http\Middleware\Authenticate)

    • Ensures the user is authenticated.
  • auth.basic (\Illuminate\Auth\Middleware\AuthenticateWithBasicAuth)

    • Implements HTTP Basic Authentication.
  • cache.headers (\Illuminate\Http\Middleware\SetCacheHeaders)

    • Sets custom cache headers for the response.
  • can (\Illuminate\Auth\Middleware\Authorize)

    • Authorizes a user for a specific ability.
  • guest (\App\Http\Middleware\RedirectIfAuthenticated)

    • Redirects authenticated users to a different page (e.g., home).
  • password.confirm (\Illuminate\Auth\Middleware\RequirePassword)

    • Ensures the user has confirmed their password recently.
  • signed (\Illuminate\Routing\Middleware\ValidateSignature)

    • Validates that the request contains a valid signature.
  • throttle (\Illuminate\Routing\Middleware\ThrottleRequests)

    • Limits the number of requests to prevent abuse.
  • verified (\Illuminate\Auth\Middleware\EnsureEmailIsVerified)

    • Ensures the user has verified their email address.

How to View and Manage Middleware

You can view all registered middleware in the app/Http/Kernel.php file and decide how to use or modify them based on your application’s needs.