Laravel AJAX Only Middleware

* It is known to work with common JavaScript frameworks: * * @see * * @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 OnlyAjaxInside this middleware enter this piece of code:/** * Handle an incoming request..* * @param IlluminateHttpRequest $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 AppHttpKernel.php under $routeMiddleware array:'only.ajax' => AppHttpMiddlewareOnlyAjax::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(AppHttpMiddlewareOnlyAjax::class);Thats it!.Now your routes are protected to only accept AJAX calls.If you have any questions, let me know!. More details

Leave a Reply