Laravel AJAX Only Middleware

Dennis Smink
2 min readDec 12, 2018

--

Sometimes you want to have a route that only accepts AJAX calls, or at least protect them if they are not AJAX calls.

Luckily Laravel has an easy helper in the Request class available for these type of things.

Please note: This tutorial is not ment as a security feature, its only a minor addition to check wether a call is AJAX.

We can use this piece of code to check if an request came in through AJAX:

$request->ajax();

Or you can use this if you want to use the Laravel helper:

request()->ajax();

This function will return a true or false based on the call is AJAX or not, if we dig deeper into this function we’ll see that its linked to another function:

/**
* Determine if the request is the result of an AJAX call.
*
* @return bool
*/
public function ajax()
{
return $this->isXmlHttpRequest();
}

The isXmlHttpRequest() function contains this:

/**
* Returns true if the request is a XMLHttpRequest.
*
* It works if your JavaScript library sets an X-Requested-With HTTP header.
* It is known to work with common JavaScript frameworks:
*
* @see http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript
*
* @return bool true if the request is an XMLHttpRequest, false otherwise
*/
public function isXmlHttpRequest()
{
return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
}

Now lets say we want to have specific routes that only accept AJAX calls, we can easily achieve this. Start by creating a middleware:

$ php artisan make:middleware OnlyAjax

Inside this middleware enter this piece of code:

/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if(!$request->ajax()){
abort(404);
}

return $next($request);
}

This will return a 404 whenever the request is not AJAX based, you can of course return any other status code you’d like to you preference.

You can register this middleware several ways to your route, you can for example add it inside your App\Http\Kernel.php under $routeMiddleware array:

'only.ajax' => \App\Http\Middleware\OnlyAjax::class,

You can then register it to your routes like so:

Route::get('/home', 'HomeController@index')->middleware('only.ajax');

You can also pass on the class to the route like so:

Route::get('/home', 'HomeController@index')->middleware(\App\Http\Middleware\OnlyAjax::class);

Thats it! Now your routes are protected to only accept AJAX calls.

If you have any questions, let me know!

--

--