Thursday, February 3, 2022

[FIXED] Enable global middleware only for one environment in Laravel 5

Issue

I'm using a global middleware in Laravel 5 (barryvdh/laravel-cors) but I only want it to be active on one environnement (dev). That's because I only require it with composer in dev environnement, so it's not installed in production.

I registered it has a global middleware in App Kernel and so I have an error if I try to deploy my app in production (Class 'Barryvdh\Cors\CorsServiceProvider' not found). I know why, but I'm looking for a solution.

Is there any way to declare a middleware globally in laravel 5 but only required in one environnement ?

I hope it's clear enough, I can edit my post if not :)


Solution

The best way I've found so far is to check env('APP_ENV') in the Kernel

public function __construct(Application $app, Router $router)
{
    if (env('APP_ENV', 'production') === 'local') {
        $this->prependMiddleware('Clockwork\Support\Laravel\ClockworkMiddleware');
    }

    parent::__construct($app, $router);
}


Answered By - EspadaV8

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.