Laravel Middleware

Laravel Middleware

Provide a convenient mechanism for filtering HTTP requests entering your application.

Verifies the user of your application is authenticated.

Can be written to perform a variety of tasks besides authentication.

  • All middleware are resolved via the service container , so you may type-hint any dependencies you need within a middleware's constructor.
  • Out of the box, the web middleware group is automatically applied to your routes/web.php file by the RouteServiceProvider.
  • A CORS middleware might be responsible for adding the proper headers to all responses leaving your application.
  • A logging middleware might log all incoming requests to your application.
  • Laravel includes a middleware that verifies the user of your application is authenticated.
  • The CSRF middleware is automatically disabled when running tests.

Defining Middleware

To create a new middleware, use the make:middleware Artisan command.

Demonstration code

php artisan make:middleware CheckAge

Demonstration code

<?php

namespace App\Http\Middleware;

use Closure;

class CheckAge
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->age <= 200) {
            return redirect('home');
        }

        return $next($request);
    }
}

Registering Middleware

Middleware Parameters

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.

Demonstration code

<?php

namespace App\Http\Middleware;

use Closure;

class CheckRole
{
    /**
     * Handle the incoming request.
     *
     * @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);
    }

}

Demonstration code

Route::put('post/{id}', function ($id) {
    //
})->middleware('role:editor');
Additional middleware parameters will be passed to the middleware after the $next argument.

Terminable Middleware

Once you have defined a terminable middleware, you should add it to the list of route or global middleware in the app/Http/Kernel.php file.

Demonstration code

<?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...
    }
}

Laravel Middleware — Structure map

Clickable & Draggable!

Laravel Middleware — Related pages: