HTTP Middleware

Introducción

Los HTTP middleware proporcionan un mecanismo de filtrado de las solicitudes HTTP que entran a tu aplicación. Por ejemplo, Laravel incluye un middleware que verifica si un usuario esté autenticado. Si el usuario no está autenticado, el middleware lo redirige a la pantalla de login. Sin embargo, si el usuario está autenticado, el middleware permitirá que la solicitud acceda a la aplicación.

Of course, additional middleware can be written to perform a variety of tasks besides authentication. Un middleware CORS podría ser responsable de agregar los encabezados adecuados a todas las respuestas de salida de tu aplicación. Un middleware de logging podría registrar todas las solicitudes entrantes a tu aplicación.

Hay varios middleware incluidos en Laravel, incluyendo middleware para mantenimiento, autenticación, protección CSRF y mucho más. Todos estos middleware se encuentran en el directorio app/Http/Middleware.

Definir middleware

Para crear un nuevo middleware, usa el comando make:middleware de Artisan:

php artisan make:middleware OldMiddleware

Este comando colocará una nueva clase OldMiddleware en tu directorio app/Http/Middleware. En este middleware, sólo permitiremos el acceso a la ruta si la edad suministrada, es mayor a 200. De lo contrario, redirigiremos a los usuarios a la URI "home".

<?php

namespace App\Http\Middleware;

use Closure;

class OldMiddleware
{
    /**
     * Run the request filter.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->input('age') <= 200) {
            return redirect('home');
        }

        return $next($request);
    }

}

As you can see, if the given age is less than or equal to 200, the middleware will return an HTTP redirect to the client; otherwise, the request will be passed further into the application. Para pasar la petición al siguiente nivel (permitiendo "pasar" al middleware), simplemente llama al callback $next con $request.

It's best to envision middleware as a series of "layers" HTTP requests must pass through before they hit your application. Each layer can examine the request and even reject it entirely.

Before / After Middleware

Whether a middleware runs before or after a request depends on the middleware itself. For example, the following middleware would perform some task before the request is handled by the application:

<?php

namespace App\Http\Middleware;

use Closure;

class BeforeMiddleware
{
    public function handle($request, Closure $next)
    {
        // Perform action

        return $next($request);
    }
}

However, this middleware would perform its task after the request is handled by the application:

<?php

namespace App\Http\Middleware;

use Closure;

class AfterMiddleware
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        // Perform action

        return $response;
    }
}

Registrar Middleware

Global Middleware

If you want a middleware to be run during every HTTP request to your application, simply list the middleware class in the $middleware property of your app/Http/Kernel.php class.

Assigning Middleware To Routes

If you would like to assign middleware to specific routes, you should first assign the middleware a short-hand key in your app/Http/Kernel.php file. By default, the $routeMiddleware property of this class contains entries for the middleware included with Laravel. To add your own, simply append it to this list and assign it a key of your choosing. Por ejemplo:

// Within App\Http\Kernel Class...

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
];

Once the middleware has been defined in the HTTP kernel, you may use the middleware key in the route options array:

Route::get('admin/profile', ['middleware' => 'auth', function () {
    //
}]);

Middleware Parameters

Middleware can also receive additional custom parameters. For example, if your application needs to verify that the authenticated user has a given "role" before performing a given action, you could create a RoleMiddleware that receives a role name as an additional argument.

Additional middleware parameters will be passed to the middleware after the $next argument:

<?php

namespace App\Http\Middleware;

use Closure;

class RoleMiddleware
{
    /**
     * Run the request filter.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string  $role
     * @return mixed
     */
    public function handle($request, Closure $next, $role)
    {
        if (! $request->user()->hasRole($role)) {
            // Redirect...
        }

        return $next($request);
    }

}

Middleware parameters may be specified when defining the route by separating the middleware name and parameters with a :. Multiple parameters should be delimited by commas:

Route::put('post/{id}', ['middleware' => 'role:editor', function ($id) {
    //
}]);

Middleware de salida

Sometimes a middleware may need to do some work after the HTTP response has already been sent to the browser. For example, the "session" middleware included with Laravel writes the session data to storage after the response has been sent to the browser. To accomplish this, define the middleware as "terminable" by adding a terminate method to the middleware:

<?php namespace Illuminate\Session\Middleware;

use Closure;

class StartSession
{
    public function handle($request, Closure $next)
    {
        return $next($request);
    }

    public function terminate($request, $response)
    {
        // Store the session data...
    }
}

The terminate method should receive both the request and the response. Once you have defined a terminable middleware, you should add it to the list of global middlewares in your HTTP kernel.