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

php artisan make:middleware CheckAge
<?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);
    }
}

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

Registering Middleware

Middleware Parameters

<?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);
    }

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

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.

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

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

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.

Laravel Middleware — Structure map

Clickable & Draggable!

Laravel Middleware — Related pages: