Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rene's avatar
Level 2

Middleware Ajax, for Angular?

Hello,

I have the following MiddleWare:

namespace App\Http\Middleware;

use Closure;

class AllowOnlyAjaxRequestsMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(!$request->ajax()) {
            return response("not allowed, only Ajax requests", 405);
        }

        return $next($request);
    }
}

```


But now I get that response when I'm doing things like this in Angular:

```
 $http.get('/foobar').success(function(foobars) {
        $scope.foobars = foobars;
    });
```
This are Ajax-request, right? Probably they aren't, because they fail... 
Who know how to protect Angularjs routes, that only then can be red by an (I thought) Ajax calls?
0 likes
1 reply
vitorarjol's avatar

@rene From the stack overflow:

When doing AJAX calls, the X-Requested-With header is often set to XMLHttpRequest. Laravel's Request::ajax() method is built on top of a Symfony2 method that simply checks for the presence of this header.

In October 2012, Angular.js removed this header because they felt that it was rarely used.

As @Thrustmaster and yourself mentioned in the comments, you need to set:

$httpProvider.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest"    

Link: http://stackoverflow.com/questions/20475460/laravel-angularjs-requestajax-always-false

Please or to participate in this conversation.