Search code examples
laravelxmlhttprequest

laravel automatically make requests to /api/... XMLHttpRequest


I need to send an XMLHttpRequest header with all my requests in order to get a JSON response

Is it possible to have this as the default behavior for all API routes?

EDIT:

laravel automatically redirects to the home route when a request fails (e.g. request validation error).

However, when I define the X-Requested-With: XMLHttpRequest header I receive a json response telling me what went wrong.

Since all my endpoints under /api are json specific I would like to default to this behavior without having to define the header.


Solution

  • You could do this with a "before" middleware, using the middleware to inject the X-Requested-With header into the request.

    Create app/Http/Middleware/ForceXmlHttpRequest.php:

    namespace App\Http\Middleware;
    
    use Closure;
    
    class ForceXmlHttpRequest
    {
        public function handle($request, Closure $next)
        {
            $request->headers->set('X-Requested-With', 'XMLHttpRequest');
    
            return $next($request);
        }
    }
    

    Apply the middleware to your api middleware group. Edit app/Http/Kernel.php:

    'api' => [
        'throttle:60,1',
        'bindings',
        \App\Http\Middleware\ForceXmlHttpRequest::class,
    ],
    

    This does, of course, take control away from the requester. As far as the framework is concerned, every request made to the api middleware group will be treated as an ajax request, and there will be no way for the requester to say otherwise. Just something to keep in mind.

    NB: untested.