Sling Academy
Home/PHP/How to Define Middleware in Laravel

How to Define Middleware in Laravel

Last updated: January 15, 2024

Introduction

Middleware in Laravel provides a convenient mechanism for inspecting and filtering HTTP requests entering your application. This tutorial will guide you through the basics of creating and using middleware in Laravel. We will begin with simple examples and gradually move to more advanced use cases.

Understanding Middleware

Middleware in Laravel is used to modify the request before it reaches the controller and the response before it’s sent back to the client. It can be used for logging, authentication, caching, etc.

Creating Middleware

To create middleware in Laravel, use the make:middleware Artisan command:

php artisan make:middleware CheckAge

This command will create a new CheckAge middleware within the app\Http\Middleware directory.

Defining Middleware Logic

Edit the generated middleware to implement your logic:

public function handle($request, Closure $next)
{
    if ($request->age 
    return $next($request);
}

Registering Middleware

Register middleware in the app\Http\Kernel.php file. You can register as a global middleware, route middleware, or group middleware.

Global Middleware

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

Route Middleware

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

To use route middleware, assign it to a route:

Route::get('profile', 'ProfileController@show')->middleware('age');

Parameters in Middleware

Middleware can also receive parameters. Let’s modify the CheckAge middleware to accept a minimum age parameter:

public function handle($request, Closure $next, $age)
{
    if ($request->age < $age) {
        return redirect('home');
    }
    return $next($request);
}

To pass a parameter to route middleware:

Route::get('profile', 'ProfileController@show')->middleware('age:18');

Middleware Groups

Laravel includes middleware groups that allow you to combine several middleware and assign them to a route or route group:

'web' => [
    \App\Http\Middleware\EncryptCookies::class,
    ...,
    \App\Http\Middleware\VerifyCsrfToken::class,
],

Apply a middleware group to routes:

Route::group(['middleware' => ['web']], function () {
    Route::get('/', function () {
        // Uses 'web' middleware group...
    });
});

Middleware Priorities

Set the order of global middleware by listing them in the $middlewarePriority array in the Kernel class:

protected $middlewarePriority = [
    \Illuminate\Session\Middleware\StartSession::class,
    \App\Http\Middleware\Authenticate::class,
    ...,
];

Terminable Middleware

Laravel allows middleware to perform tasks after the response has been sent to the browser:

public function terminate($request, $response)
{
    // Perform some action
}

The terminate method is only called if your middleware implements the Terminable interface.

Testing Middleware

Test your middleware by defining tests that make HTTP requests to your application and asserting the expected behavior:

public function testMiddleware()
{
    $response = $this->get('profile');
    $response->assertStatus(302);
}

Advanced Middleware Usage

For more complex applications, middleware can be used in advanced scenarios, such as rate limiting, CORS, or transforming the response data into a specific format.

Using Middleware to Transform Responses

Middleware can modify responses just before they are sent to the client:

public function handle($request, Closure $next)
{
    $response = $next($request);
    // Modify the response here
    return $response;
}

Dynamic Middleware Assignment

Laravel allows assigning middleware dynamically from a controller’s constructor or method:

public function __construct()
{
    $this->middleware('age', ['only' => ['show']]);
}

Conclusion

In this guide, we have explored the different ways to define, register, and implement middleware in Laravel, from basic to advanced use cases. With this knowledge, you can customize the request and response cycle to suit your application’s needs effectively.

Next Article: How to assign middleware to routes in Laravel

Previous Article: Laravel: How to define custom Blade directives

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array