C
C
Corsair_TM2019-09-09 18:01:02
Laravel
Corsair_TM, 2019-09-09 18:01:02

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);
    }

Registered it in Kernel.php
protected $routeMiddleware = [
        .....
        'ajax' => \App\Http\Middleware\OnlyAjaxRequest::class
    ];

Roth wrote:
Route::post('/product/handle', 'Page\[email protected]')->middleware('ajax');

If you drive the address / product / handle into the address bar of the browser, the idea is to issue a 404 page.
Disabled the debugger, shows the message "Whoops, looks like something went wrong." instead of 404 pages.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Daria Motorina, 2019-09-09
@Corsair_TM

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 question

Ask a Question

731 491 924 answers to any question