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
app/Http/Middleware/RestrictIpAddressMiddleware.php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class RestrictIpAddressMiddleware
{
// Blocked IP addresses
public $restrictedIp = ['192.168.0.1', '202.173.125.72', '192.168.0.3', '202.173.125.71'];
/**
* 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
app/Http/Kernel.php
protected $middlewareGroups = [
'web' => [
...
...
...
\App\Http\Middleware\RestrictIpAddressMiddleware::class,
],
'api' => [
'throttle:api',
...
],
];
i hope you like this solution.