Chapter 7. Filtering Requests with Middleware

In this chapter, middleware will be discussed in detail and examples from the accommodation software will be provided. Middleware is a great mechanism to help separate a software application into separate layers. To illustrate this principle, middleware provides layers of protection around the innermost part of the application, which could be thought of as the kernel.

In Laravel 4, middleware was known as filters. These filters were used in routing to perform actions that came before the controller like authentication, where the user would be filtered based on certain criteria. Also, the filters could come after the controller.

In Laravel 5, the concept of middleware, which was already present but not prominent in Laravel 4, is now brought into the foreground into the actual request workflow and can be used in various ways. Think of it as a Russian doll, where each doll represents a layer in the application—having the correct credentials will allow us to enter deeper into the application.

The HTTP kernel

The file located at app/Http/Kernel.php is a file that manages the configuration of the kernel of the program. The basic structure is as follows:

<?php namespace AppHttp;

use IlluminateFoundationHttpKernel as HttpKernel;

class Kernel extends HttpKernel {

  /**
   * The application's global HTTP middleware stack.
   *
   * @var array
   */
  protected $middleware = [
  'IlluminateFoundationHttpMiddlewareCheckForMaintenanceMode',
    'IlluminateCookieMiddlewareEncryptCookies',
    'IlluminateCookieMiddlewareAddQueuedCookiesToResponse',
    'IlluminateSessionMiddlewareStartSession',
    'IlluminateViewMiddlewareShareErrorsFromSession',
    'IlluminateFoundationHttpMiddlewareVerifyCsrfToken',
  ];

  /**
   * The application's route middleware.
   *
   * @var array
   */
  protected $routeMiddleware = [
    'auth' => 'AppHttpMiddlewareAuthenticate',
    'auth.basic' => 'IlluminateAuthMiddlewareAuthenticateWithBasicAuth',
    'guest' => 'AppHttpMiddlewareRedirectIfAuthenticated',
  ];

}

The $middleware array is a list of middleware classes and their namespace, and it is executed at every request. The $routeMiddleware array is a key and value array that is created as list of aliases that can be used together with routes to filter requests.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset