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 :)
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() .
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.
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.
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;
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With