Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable global middleware only for one environment in Laravel 5

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 :)

like image 533
rap-2-h Avatar asked Feb 11 '15 11:02

rap-2-h


People also ask

Can we apply two middleware on a single route?

We can use more than one middleware on an Express app instance, which means that we can use more than one middleware inside app. use() or app. METHOD() .

Is it allowed to have multiple middleware for same path?

We can also attach more than one middleware function to a route to apply multiple stages of processing. Our route with multiple middleware functions attached will look like this: const express = require('express') const app = express() // handle post request for path /products app.

How can you assign the middleware in Laravel?

Assigning Middleware To Routes If you would like to assign middleware to specific routes, you should first assign the middleware a key in your application's app/Http/Kernel.php file. By default, the $routeMiddleware property of this class contains entries for the middleware included with Laravel.


2 Answers

I am new to SO so I am not allowed to comment other answers. I know this is an old topic but thanks to search you still find it.

In the accepted answer a user asked:

When I try this in app/Http/Kernel.php I get ( ! ) Fatal error: Uncaught exception 'ReflectionException' with message 'Class App\Http\Application does not exist' in /home/vagrant/earthport/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 836

I also had this issue and basically you just need to make sure to include the classes

use Illuminate\Contracts\Foundation\Application;
use Illuminate\Routing\Router;
like image 190
user17789225 Avatar answered Oct 14 '22 04:10

user17789225


To achieve this simply load kernel in the service provider then call either pushMiddleware or prependMiddleware

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot(Kernel $kernel)
    {
        if ($this->app->environment() === 'dev') {
            $kernel->prependMiddleware(ClockworkMiddleware::class);
        }
    }
}
like image 42
ralphowino Avatar answered Oct 14 '22 04:10

ralphowino