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:
Or you can use this if you want to use the Laravel helper:
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()
isXmlHttpRequest() function contains this:
* Returns true if the request is a XMLHttpRequest.
* @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)
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
'only.ajax' => \App\Http\Middleware\OnlyAjax::class,
You can then register it to your routes like so:
You can also pass on the class to the route like so:
Thats it! Now your routes are protected to only accept AJAX calls.
If you have any questions, let me know!