(Laravel 5 - AngularJS) Request::ajax() returns false

(Laravel 5 – AngularJS) Request::ajax() returns false

I am using Laravel 5.2 and AngularJS 1.4.8, but this behaviour of Laravel appears in version 5.0 (and above) too.

I was checking in a middleware if the request is an ajax request, so I can handle it differently. What I wasn’t expected, that my AngularJS call isn’t interpreted like an ajax call. Here is my code:

// middleware (handling admin roles)
public function handle($request, Closure $next, $guard = null) {
    if (Auth::guard($guard)->guest()) {
        if ($request->ajax()) {
            return response('Unauthorized.', 401);
        } else {
            return redirect()->guest('login');
    } else if (!Auth::guard($guard)->user()->isAdmin) {
          return redirect()->to('/')->withError('Permission Denied');

    return $next($request);

I tested if I can access the admin route from an ajax call (just to be sure), and I expected to get the 401 error, but I didn’t.

The problem is that when doing AJAX calls, the X-Requested-With header is often set to XMLHttpRequest. The Request::ajax() method from Laravel 5.* is built on top of a Symfony2 method. This simply checks if this header is present, nothing more. This header was removed from AngularJS in late 2012, because they felt that it wasn’t really used.

The solution is to set the X-Requested-With parameter in AngularJS. It can be done like this:

app.config(function($httpProvider) {
    $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

Cheers! Happy Coding!

Adam Brown
Please follow and like us:

Leave a Comment