Skip to content

Instantly share code, notes, and snippets.

@nmfzone
Last active February 15, 2021 02:16
Show Gist options
  • Save nmfzone/73043dc67d707993b9edb2be3b35adaf to your computer and use it in GitHub Desktop.
Save nmfzone/73043dc67d707993b9edb2be3b35adaf to your computer and use it in GitHub Desktop.
Extending Laravel Illuminate\Routing\Router
  1. Extend the Illuminate\Routing\Router to the (for example) App\Illuminate\Routing\Router.
  2. Add method setMiddleware and setMiddlewareGroups to your App\Illuminate\Routing\Router
<?php

namespace App\Illuminate\Routing;

use Illuminate\Routing\Router as BaseRouter;

class Router extends BaseRouter
{
    ......

    /**
     * Set the middleware.
     *
     * @param  array  $middleware
     * @return void
     */
    public function setMiddleware(array $middleware)
    {
        $this->middleware = $middleware;
    }

    /**
     * Set the middleware groups.
     *
     * @param  array  $middlewareGroups
     * @return void
     */
    public function setMiddlewareGroups(array $middlewareGroups)
    {
        $this->middlewareGroups = $middlewareGroups;
    }
}
  1. Add method setRouter to your App\Http\Kernel
<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;
use Illuminate\Routing\Router;

class Kernel extends HttpKernel
{
    ......

    /**
     * Set the router instance to the Kernel.
     *
     * @param  \Illuminate\Routing\Router  $router
     * @return void
     */
    public function setRouter(Router $router)
    {
        $this->router = $router;
    }
}
  1. Add below to your App\Providers/AppServiceProvider, on the register method.
use App\Illuminate\Routing\Router;

......

$this->app->booted(function () {
    $newRouter = new Router($this->app['events'], $this->app);
    $newRouter->setRoutes($this->app['router']->getRoutes());
    $newRouter->setMiddleware($this->app['router']->getMiddleware());
    $newRouter->setMiddlewareGroups($this->app['router']->getMiddlewareGroups());
    $newRouter->middlewarePriority = $this->app['router']->middlewarePriority;

    $this->app['router'] = $newRouter;

    $kernel = $this->app->make(\Illuminate\Contracts\Http\Kernel::class);
    $kernel->setRouter($newRouter);
});
  1. Done.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment