Detailed explanation of three scenarios of Laravel5.1 framework registration middleware

  • 2021-12-12 08:13:21
  • OfStack

In this paper, three scenarios of Laravel 5.1 framework registration middleware are described as examples. Share it for your reference, as follows:

There are three main scenarios for registering middleware in Laravel, one is to register the method in the controller, the other is to register the whole controller, and the last one is to register the middleware globally.

1. Register middleware in a method in the controller

This requirement is the most common, and this example is to add middleware to the index method in IndexController.


Route::get('/', ['middleware'=>['App\Http\Middleware\EmailMiddleware'],'uses'=>'IndexController@index']);

2. Register middleware in the whole controller

This requirement sometimes arises. If middleware is registered in the whole controller, all methods in this controller are registered with the middleware. Come with me to find the answer!

Controller base class (Controller. php)

First of all, look at the controller base class under 1. You can see that the Controller class inherits the BaseController class, and the path of BaseController is Illuminate\ Routing\ Controller. Then let's look at the source code of Laravel.


<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
abstract class Controller extends BaseController
{
  use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}

Class BaseController

From the source code, we can see that there is a property for middleware, this middleware property is what we are looking for, so as long as we need to register the controller under the use of this property can complete the registration.


protected $middleware = [];


<?php
namespace Illuminate\Routing;
use BadMethodCallException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
abstract class Controller
{
  /**
   * The middleware registered on the controller.
   *
   * @var array
   */
  protected $middleware = [];
  /**
   * Register middleware on the controller.
   *
   * @param array|string|\Closure $middleware
   * @param array  $options
   * @return \Illuminate\Routing\ControllerMiddlewareOptions
   */
  public function middleware($middleware, array $options = [])
  {
    foreach ((array) $middleware as $m) {
      $this->middleware[] = [
        'middleware' => $m,
        'options' => &$options,
      ];
    }
    return new ControllerMiddlewareOptions($options);
  }
  /**
   * Get the middleware assigned to the controller.
   *
   * @return array
   */
  public function getMiddleware()
  {
    return $this->middleware;
  }
  /**
   * Execute an action on the controller.
   *
   * @param string $method
   * @param array  $parameters
   * @return \Symfony\Component\HttpFoundation\Response
   */
  public function callAction($method, $parameters)
  {
    return call_user_func_array([$this, $method], $parameters);
  }
  /**
   * Handle calls to missing methods on the controller.
   *
   * @param array  $parameters
   * @return mixed
   *
   * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
   */
  public function missingMethod($parameters = [])
  {
    throw new NotFoundHttpException('Controller method not found.');
  }
  /**
   * Handle calls to missing methods on the controller.
   *
   * @param string $method
   * @param array  $parameters
   * @return mixed
   *
   * @throws \BadMethodCallException
   */
  public function __call($method, $parameters)
  {
    throw new BadMethodCallException("Method [{$method}] does not exist.");
  }

Register middleware for the entire controller

We choose the Authenticate middleware of the system as an example, which is used to detect whether the user is logged in.

Note: The middleware name is a key, and the value can be an empty array


protected $middleware = ['\App\Http\Middleware\Authenticate'=>[]];

3. Register middleware globally

Open app/Http/Kernel. php, which is a kernel file, and you can see a property $middleware. We just need to add the path of our custom middleware to this property $middleware.

There is also a $routeMiddleware attribute, which allows you to register the middleware based on the route.
Our routers are: goods/info, goods/detail
We can add 1 line to the $routeMiddleware attribute


'goods.*' => \App\Http\Middleware\GoodsMiddleware::class,


<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
  /**
   * The application's global HTTP middleware stack.
   *
   * @var array
   */
  protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\VerifyCsrfToken::class,
  ];
  /**
   * The application's route middleware.
   *
   * @var array
   */
  protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
  ];
}

For more readers interested in Laravel related content, please check the topics on this site: "Introduction and Advanced Tutorial of Laravel Framework", "Summary of Excellent Development Framework of php", "Introduction Tutorial of php Object-Oriented Programming", "Introduction Tutorial of php+mysql Database Operation" and "Summary of Common Database Operation Skills of php"

I hope this article is helpful to the PHP programming based on Laravel framework.


Related articles: