Home > database >  Laravel dependency injection when setting controllers to a route
Laravel dependency injection when setting controllers to a route

Time:10-05

I'm looking for a good solution to allow users of my package to change controllers that are bound to routes. Currently I have found this solution:

Route::get('/settings', app(OverviewController::class)::class)->name('settings.overview');

But this seems kind of inefficient as the method doesn't accept an object, only the class name. Is there a better way of using dependency injection for this purpose?

Another solution would be using config files but I want to avoid that as I want other packages to be able to inject whatever as well.

If it's not possible to use dependency injection for this purpose, what are better solutions short of creating my own system?

CodePudding user response:

Laravel will use it's dependency management when resolving that class (see Illuminate\Routing\Route::getController). You can just do this:

Route::get('/settings', OverviewController::class)
  • Related