How to attach middleware to an existing named route from a package in laravel 5?

Viewed 172

I'm trying to extend an existing application without modifying its source code. The application has a named route called wizard-add. Is there a way to register \MyPackage\MyMiddleware with the existing route? I tried attaching it via Route::getRoutes()->getByName('wizard-add')->middleware(\MyPackage\MyMiddleware::class); but since packages are registered before the routes are read, Route::getRoutes() returns an empty collection.

Thank you!

1 Answers

Since I didn't find a way to solve this, I extended the app's controllers and put my logic inside.

namespace MyPackage\Controllers;
use App\Controllers\WizardController;

class MyPackageWizardController extends WizardController { ... }

and then in my service provider's register() method:

$this->app->bind(WizardController::class, MyPackageWizardController::class);

So everytime the app attempts to instantiate WizardController, it instantiates MyPackageWizardController instead. I don't know if there are any drawbacks but so far this has been working perfectly for me.

Related