Middleware are used to create a layer between request and response of the HTTP request. It filters or create a logic before the request serve to the controller and also filter or modify the response. We can also use it to validate the user auth, JSON request to manipulate the request and response.

In this example, we will execute a user check with status in not block by admin. If it’s blocked by admin then show the response accordingly.

Let’s begin with simple example and step by step process:

Create Middleware

First step is to create the middleware using the Laravel artisan command or manually, so open the terminal at project location and run below command:

php artisan make:middleware CheckBlacklist

Above command will create a middleware at location app\Http\Controllers\Middleware or you can also create the same manually at same location without artisan command.

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

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

Register new middleware in Kernel

Now, go to app/http/kernel.php and register the new middleware.

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    ....


    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        ....
        'checkBlacklist' => \App\Http\Middleware\CheckBlacklist::class,
    ];
}

Implement the logic in middleware

We have created our custom middleware and defined in kernel, now it's time to implement the our core logic for check blacklisted user.

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CheckBlacklist
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if (auth()->user()->is_blacklisted == 0) {
            return $next($request);
        }

        return response()->json('Your account is blacklisted by admin'); 
   }
}

Here, we added the simple logic to check is the user is blacklisted or not.

Create the route and add middleware

It's time to add our new middleware to the our route so we can validate the request.

Route::get('create', [PostController::class, 'create'])->middleware(CheckBlacklist::class);