CodeBriefly
Tech Magazine

Understanding Laravel Middleware

2 3,778

Get real time updates directly on you device, subscribe now.

In this article, we will discuss Laravel Middleware. As per the name Middleware, Its like a mechanism which works between HTTP Request and Response. Laravel has default middleware for user authentication, CSRF token verification and etc.

Creating Laravel Middleware

Laravel ships with the artisan feature. Artisan is a command-line interface, It provides the number of artisan commands which help us in our development. We will discuss Artisan later. Let’s back to our Middleware.

As I mentioned, The given Artisan command help us to create Middleware.

php artisan make:middleware AjaxRequest

This command creates the Middleware named AjaxRequest. We will use this middleware to check our application request, which request is ajax request or not.

Our AjaxRequest middleware is located at app/Http/Middleware. Middleware contains default handle function.

<?php

namespace App\Http\Middleware;

use Closure;

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

Let’s add some logic to check ajax requests.

<?php

namespace App\Http\Middleware;

use Closure;

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

In this code example, I’m using the $request->ajax() default Laravel function. Determine if the request is the result of an AJAX call. Also, using abort function to show error on unauthorized access to our application. You can get more information on exceptions here.

Before and After Request

In Middleware, we can run our logic before and after Http request. Let’s show you with the small example:

Before the request is handled by the Laravel App.

<?php

namespace App\Http\Middleware;

use Closure;

class BeforeRequest
{
    public function handle($request, Closure $next)
    {
       // Add Logic

       return $next($request);
    }
}

After the request is handled by the Laravel App.

<?php

namespace App\Http\Middleware;

use Closure;

class AfterRequest
{
    public function handle($request, Closure $next)
    {
       $response = $next($request);

       // Add Logic

       return $response;
    }
}

Now, time to make our middleware functional. Let’s Register the middleware.

Global Middleware: Add middleware class in the $middleware property of app/Http/Kernel.php class.

Assign Middleware to Route: You need to assign the middleware in app/Http/Kernel.php. If you want to assign middleware to specific routes. By default, $routeMiddleware property of the class contains all middleware entries.

...
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,

        // Custom Middlewares
        'ajax' => \App\Http\Middleware\AjaxRequest::class
    ];
...

In the above code example, we are registering our AjaxRequest Middleware class in the $routeMiddleware. Now, It’s available for our use. Let’s discuss how can use this with an app.

We are using middleware method to assign middleware to a route.

Route::get('/user/get','UserController@getUser')->middleware('ajax');

Multiple middlewares on a single route.

Route::get('/user/get','UserController@getUser')->middleware('ajax','auth');

Assigning middleware to the group of routes.

// auth middleware to group route.
Route::group([middleware => ['auth']], function() {
    Route::get('/user/get','UserController@getUser');
    Route::post('/user/store','UserController@store');
    ...
});

// auth and web Middleware to group route.
Route::group([middleware => ['auth','web']], function() {
    Route::get('/user/get','UserController@getUser');
    Route::post('/user/store','UserController@store');
    ...
});

Conclusion: Middleware is the best way to filter the HTTP request. We will discuss more on Middleware and other Laravel features. Feel free to comment for any query.

If you like our content, please consider buying us a coffee.
Thank you for your support!
Buy Me a Coffee

Get real time updates directly on you device, subscribe now.

2 Comments
  1. Silambarasan RD says

    In AfterRequest class you’ve put logic after the return $next($request); is not correct. Anything after return statement will be ignored. Please check once.

    1. Pankaj Sood says

      Thanks, good catch…
      Code is updated now… 🙂

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. AcceptRead More