Laravel Examples
Adding Quill Editor in Laravel 10 using Vite
How to add Facebook Messenger to a Website
Caching in Laravel 8/9/10 with Example
Clearing Cache in Laravel 8/9/10
Programmatically Block IP Addresses in Laravel 8/9/10
Implementing Authentication in Laravel 8/9 using Bootstrap UI
Install Composer
How to Deploy a Laravel Project on CPanel
Integrate Summernote Editor into a Laravel Project
Fixing Summernote Dropdown issue with Bootstrap 5
Programmatically Block IP Addresses in Laravel 8/9/10
- Last updated Apr 25, 2024
In this tutorial, we will learn how to programmatically block a user's IP address from accessing a Laravel website.
To block IP addresses in Laravel, do the following:
- Create a middleware named RestrictIpAddress in the app\Http\Middleware directory of your Laravel application by executing the following command in your terminal:
- After creating the RestrictIpAddress middleware file, paste the following code into the file:
- Next, you need to register the middleware you just created in the app\Http\Kernel.php file within the $middlewareGroups array, as shown in the example below:
- Run and test your application. If you visit your website from the restricted IP address, you will see the message "You are not authorized to access this site". in your browser:
php artisan make:middleware RestrictIpAddress
<?php
namespace App\Http\Middleware;
use App\Http\Util\RemoteUser;
use Illuminate\Support\Facades\Log;
use Closure;
class RestrictIpAddress
{
// add ip addresses to block
public $restrictIpAddrs = ['127.0.0.1', 'ip2', 'ip3', 'ip4'];
public function handle($request, Closure $next)
{
$remoteUserIP = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
if (in_array($remoteUserIP, $this->restrictIpAddrs)) {
//use this incase you want to show the attacker a custom message
//return response()->json(['message' => "You are not authorized to access this site."]);
//make invalid redirect using double forward slash so that attacker is redirected to unknown error
return Redirect::to('//error');
}
return $next($request);
}
}
protected $middlewareGroups = [
'web' => [
//other middlewares
\App\Http\Middleware\RestrictIpAddress::class,
],
'api' => [
'throttle:api',
//middlewares
],
];