Answer the question
In order to leave comments, you need to log in
How to limit routes only for AJAX requests?
Good afternoon, I'm trying to limit the route only for AJAX requests, but it doesn't work. Found this way, but it doesn't work, I'm using the latest version of Laravel.
Created the OnlyAjaxRequest.php mediator
public function handle($request, Closure $next)
{
if ($request->ajax()) {
return $next($request);
}
abort(404);
}
protected $routeMiddleware = [
.....
'ajax' => \App\Http\Middleware\OnlyAjaxRequest::class
];
Route::post('/product/handle', 'Page\[email protected]')->middleware('ajax');
Answer the question
In order to leave comments, you need to log in
I moved the code from your example and I think I reproduced the problem - if you send a non-ajax request via postman, then everything is OK, the middleware works. Debug in .env disabled. Usually, the POST method is used to send data via ajax, but if you use GET (drive the URL into the address bar of the browser), then the first error will be 405 (method not allowed), but the default text will be "Oops, something went wrong" (for the 500th error, it the same), i.e. the wrong method error is processed earlier than the middleware code.
If this case does not solve the problem, then let's look at the entire chain of code.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question