Menu

AJAX Middleware in Laravel

The middleware system is a very important and useful part of a Laravel application. It offers protection and filters for HTTP requests.

Laravel comes with some middlewares by default, but there are some cases where our app requires some special filter. For example let’s assume we want to filter the AJAX requests for some route and if the request is not AJAX return with a forbidden (403) HTTP status code.

Laravel provides us a middleware generator command out of the box, so we don’t have to create the file manually. After running the command php artisan make:middleware AjaxMiddleware, our file is ready, and located in the app/Http/Middlewares directory.

Our fresh middleware looks like this:

namespace App\Http\Middleware;

use Closure;

class AjaxMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request);
    }
}

Fortunately, with Laravel’s Request api we can easily check the type of a request. For example we can to the following to check if the current request is an AJAX one: $request->ajax(). Thats it. There is nothing left, but implement an if statement with the request check, and give the correct response to the user.

public function handle($request, Closure $next)
{
    if (! $request->ajax()) {
        return abort(403);
    }

    return $next($request);
}

We have to assign the middleware to the route, where we want to handle request like this. We can do this in our routes file:

Route::get('/api', ['middleware' => ['api', 'ajax'], function() {
    //
}]);

For further reading, and the documentation take a look at this:  https://laravel.com/docs/master/middleware

Have something on your mind?