1
votes

I'm having a route group that looks following:

web.php

Route::group( ['middleware' => 'auth', 'prefix' => 'ajax'],
    function() {
        Route::post( 'checkTheName', function( Request $request ) {
            return response()->json( 'Something important' );
        } );
    }
);

Is this possible with Laravel to check whether incoming request is an AJAX request for all routes in a group (and if not, throw eg. a 404 status)? I find it kinda pointless checking it within every child route post. Thats why I would like to make a global check if request is within the route group scope.

Using Laravel 5.5

2

2 Answers

3
votes

You can achieve this by using middleware and using this to check if the request is an Ajax request or not.

You can create new middleware with php artisan make:middleware AjaxMiddleware.

Inside the handle function you might look to do something like this:

public function handle($request, Closure $next)
{
    abort_unless($request->ajax(), 404);
}

This takes advantage of the abort_unless() helper which takes a conditional statement as the first parameter and then the status code to return in the second. You may also choose to do abort_unless($request->ajax(), 401) which would be an unauthorised request.

You then just need to register the middleware in your Kernel.php file and either apply it in your route group or on your controller constructor.

1
votes

The correct way to do this, is to return the next variable in every middleware handle. Above method with abort_unless will actually not work in Laravel 6. Have not tested on previous versions.

if(!$request->ajax()) {
    abort(404);
} else {
    return $next($request);
}

Even better is to return 401 instead of 404, since it probably is an unauthorized request.