Search code examples
phplaravelmiddleware

How to register middleware in Kernel in Laravel


I have created this middleware which I want to use for domain and subdomains (myapp.com, comany1.myapp.com) routing in multi-company application:

namespace App\Http\Middleware;


use App\Models\Organization\OrgCompany;
use Closure;

class VerifyAppDomain
{
    public function handle($request, Closure $next)
    {
        $request->get('domain_name', $this->getBaseDomain());

        $company = OrgCompany::where('subdomain', $subdomain)->firstOrFail();

        $request->session()->put('subdomain', $company);

        return $next($request);
    }

    protected function getBaseDomain()
    {
        return config('myconfig.default_domain_name', 'myapp');
    }
}

route/web.php

Route::domain('myapp')->group(['middleware' => ['veryfy_app_domain']], function () {
    
    Route::group(['prefix' => '/' . $defaultDomain], function () {
        Route::get('/', function ($id) {
               //
        });     
    });

});

I have all these in kernel:

protected $middlewareGroups = [
    'web' => [
 
    ],
];

protected $routeMiddleware = [

];

protected $middlewarePriority = [

];

Solution

  • How to write and register a middleware is described inside the Laravel docs.

    For your VerifyAppDomain middleware you should go to app/Http/Kernel.php file and check the protected $middlewareGroups property.

    I suppose you want this middleware run for each request, so you could add it to the web group. That would mean that you do not need to specify this middlware separately in your routes.php file. It would automatically be applied to all routes that use the web middleware.

    If you don't want to have this automatically applied, use the $routeMiddelware property.

    protected $routeMiddleware = [
        //.. others
        'verify_app_domain' => \App\Http\Middleware\VerifyAppDomain::class,
    ]