Laravel Dependency Injection in Middleware
You are not allowed to change the method signature here. Simply you may use something like this:
public function handle($request, Closure $next) {
// Get the bound object to this interface from Service Provider
$authClient = app('App\Services\Contracts\AuthClientInterface');
// Now you can use the $authClient
}
Also, you may use a __construct
method to achieve that, check the answer given by - Francis.TM
.
You cannot do dependency injection at handle
method in a Request directly, do that in a constructor.
Middleware is invoked by call_user_func
, so any injection here will not be work.
<?php
namespace App\Http\Middleware;
use Closure;
use App\Foo\Bar\AuthClientInterface; # Change this package name
class FooMiddleware
{
protected $authClient;
public function __construct(AuthClientInterface $authClient)
{
$this->authClient = $authClient;
}
public function handle(Request $request, Closure $next)
{
// do what you want here through $this->authClient
}
}
Laravel's IoC only handles constructor method injection for all objects by default. The IoC will only inject dependencies into functions/methods handled by the router. The can be a closure used to handle a route, or more commonly, Controller methods used to handle routes.
The IoC does not do method dependency injection for any other object by default. You can call methods yourself through the IoC and have it resolve dependencies, but the framework only does this itself for route handlers. You can take a look at this question/answer for a little more information on using method dependency injection outside of a controller: can I use method dependency injection outside of a controller?.
Handling this by injecting your dependency through your constructor is the correct way to go, if you want to continue to use dependency injection.