Custom Middleware in laravel

How to create custom middleware and use it in laravel

Before we see how you can create your own custom middleware in laravel, let’s see what is middleware in the first place.

So, What is middleware in laravel anyway?

Just as the name suggests, middleware is an application code block that will be executing before your application logic. 

So, if you want to perform some action on specific/all request that is coming to your application before processing it, say for example checking if the user is authenticated or not then you can use the middleware.

Laravel provides many middleware out of the box but we can also create middleware as per our needs. Now let’s go through it in brief.

Create Custom Middleware:

We can create a custom middleware using below artisan command, so open up your terminal and run the command:

php artisan make:middleware YourMiddlewareName

This command will create a file in app/Http/Middleware directory, it should look something like this

<?php

namespace App\Http\Middleware;

use Closure;

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

So, the basic structure is ready and now you just have to add your custom code in the handle method. 

Did you notice the $next($request) that is already available in the handle method?, What this does is to pass your incoming request to further down for processing. So you want to do something before processing your request then you have to add that code above that and if you want to perform some action after processing the request then you have to add code below that. We will see example for both for more understanding.

Let’s create one middleware to check if logged in user is active or not

Run php artisan make:middleware CheckIsActiveUser to generate middleware scaffoldings.

Now, copy below code snippets and paste it in your newly generate middleware at app/Http/Middleware/CheckIsActiveUser.php file:
<?php

namespace App\Http\Middleware;

use Closure;

class CheckIsActiveUser
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
	   if(auth()->user()->is_active == 1){
        return $next($request);
    }
        return redirect('login')->with('error','You are not active user, please contact admin.');
    }
}

In the above code snippets, we are checking that the current auth user is active or not, if he/she is active then proceed the request else return a redirect to the login page with the error message “You are not an active user, please contact admin”.

As you can see in the above example, we are checking for conditions before $next($request) is called because we want to process requests further only if the user is active.

Read Also: Creating Custom Validation in Laravel

Here is one more example for middleware to implement CORS for our API

Run php artisan make:middleware CORS to generate middleware scaffoldings.

Now, copy below code snippets and paste it in your newly generate middleware at app/Http/Middleware/CORS.php file:

<?php

namespace App\Http\Middleware;

use Closure;

class CORS
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
		// Preparing headers
		header("Access-Control-Allow-Origin: *"); // This will allow request from all origin
		
		$headers = [
            'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers'=> 'X-Requested-With, Content-Type, X-Auth-Token, Origin'
        ];
	
	
		// Response to preflight request
		if($request->getMethod() == "OPTIONS") {
			return Response::make('OK', 200, $headers);
		}
		
		// Process the request further
		$response = $next($request);
		
		// Add headers in our response
        foreach($headers as $key => $value) {
            $response->header($key, $value);
		}
		
        return $response;
    }
}

Here, You can see that we want to add CORS headers in our response.

That means that we have to add it in our response, so we have added that code after $next($request).

Extra, CORS (Cross-Origin Resource Sharing) is a mechanism that is used by browser to determine that if they should allow request from one origin to make request to different origin based on additional HTTP Headers, So, if your api is hosted at api.example.com and you want to access that API from example.com then you need to implement CORS in your API or else request will fail.

Registering Custom Middleware:

After creating our middleware, we’ve to register our custom middleware in the kernel.php file inside /app/Http/ directory.

Open up the kernel.php file and register this custom middleware inside $routeMiddleware section as shown below:

/**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\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,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'CheckIsActiveUser'=> \App\Http\Middleware\CheckIsActiveUser::class,  <-- add this line
        'CORS'=> \App\Http\Middleware\CORS::class,  <-- add this line
    ];

Applying Middleware to Routes:

If we want to apply middleware to the specific routes, we can do it as below in web.php file:

Route::get('dashboard', function () {
    //Codes here
})->middleware('CheckIsActiveUser');

We can also define multiple middleware to one routes as below:

Route::get('dashboard', function () {
    //Some Code here
})->middleware('CheckIsActiveUser', 'CORS');

Applying Middlewares to group of Routes:

In some scenario, multiple routes can have same middleware and at that time instead of applying middleware to every routes we can use route group and apply middleware to that group as shown below:

Route::group(['middleware' => ['CheckIsActiveUser', 'CORS']], function () {
    //Some Code Here...
});

That’s it, Here we have learned the followings, how to create custom middleware in Laravel, how to register middleware in our application and how to use it in our routes.

As a bonus you have also learned what is CORS and how to implement CORS in laravel application.

Leave a Reply

Your email address will not be published. Required fields are marked *