I want to use VacancyListRequest
to pass through middleware parameters and use its rules to validate them before controller action. I know that middleware acts Pipeline pattern, but does anybody know how to use any custom type except default IlluminateHttpRequest
?
Middleware
public function handle(VacancyListRequest $request, Closure $next)
{
$request = $this->analizeQuery($request);
$request = $this->formatValues($request);
$request = $this->prepareParams($request);
return $next($request);
}
Controller
public function index(VacancyListRequest $request, bool $asQuery = false)
Error
AppHttpMiddlewareVacancyBeforeVacancyIndexRequestMiddleware::handle(): Argument #1 ($request) must be of type AppHttpRequestsVacancyVacancyListRequest, IlluminateHttpRequest given,
Advertisement
Answer
You are getting that error because you are passing the $request
as argument of the handle method of you middleware which is typed as VacancyListRequest
instead of being of type IlluminateHttpRequest
.
You should change the middleware to be like this
use IlluminateHttpRequest;
use Closure;
class VacancyListRequest
{
/**
* Handle an incoming request.
*
* @param IlluminateHttpRequest $request
* @param Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
$request = $this->analizeQuery($request);
$request = $this->formatValues($request);
$request = $this->prepareParams($request);
return $next($request);
}
}
But in your controller It should be like this
// At the top of you controller file you add this
use AppHttpRequestsVacancyVacancyListRequest;
// And define the controller method like this
public function index(VacancyListRequest $request, bool $asQuery = false)
It’s a must for the first parameter of the
handle
method to be of typeIlluminateHttpRequest
like it defined in the docs # Defining Middleware