Laravel 8 - How to Restrict or Block User Access via IP Address


In this article, I will share with you how to Restrict or Block User Access via IP Address in Laravel 8 with example. Many times you need to block some user access on IP address base then here i will share with you a very simple example of how to do it in your laravel application. 

Create Block IP Middleware

First create the middleware in your laravel application using the following artisan command.

php artisan make:middleware RestrictIpAddressMiddleware


namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class RestrictIpAddressMiddleware
    // Blocked IP addresses
    public $restrictedIp = ['', '', '', ''];

     * Handle an incoming request.
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
    public function handle($request, Closure $next)
        if (in_array($request->ip(), $this->restrictedIp)) {
            return response()->json(['message' => "You are not allowed to access this site."]);
        return $next($request);

Add Middleware in Kernel

now add your created middleware in kernel


protected $middlewareGroups = [
        'web' => [

        'api' => [

i hope you like this solution.