Hello developer! In this article, we'll see laravel 10 restricts user access from IP addresses. Here, you can blacklist/whitelist IP addresses in laravel 10. Additionally, block IP addresses from selected countries.
We use middleware to restrict or block the user's IP address in laravel 10. Also, we will see how to create middleware and block IP addresses to access URLs.
How to Block IP Address in Laravel 10
We'll install the laravel 10 application using the following composer command.
composer create-project laravel/laravel laravel_10_example
Then, we will create a BlockIPAddressMiddleware file using the following command.
php artisan make:middleware BlockIPAddressMiddleware
app/Http/Middleware/BlockIPAddressMiddleware.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class BlockIPAddressMiddleware
{
public $blockIPs = ['Block-IP-1', 'Block-IP-2', 'Block-IP-3'];
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
if (in_array($request->ip(), $this->blockIPs)) {
abort(403, "You are restricted to access the site.");
}
return $next($request);
}
}
Next, we will register the middleware file to the kernel.php file.
app/Http/Kernel.php
<?php
namespace App\Http;
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 = [
....
'blockIPAddress' => \App\Http\Middleware\BlockIPAddressMiddleware::class,
];
}
Now, we will use the BlockIPAddressMiddleware in the route file. So, add the following code to the web.php file.
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
use App\Http\Controllers\PostController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::middleware(['blockIPAddress'])->group(function () {
Route::resource('users', UserController::class);
Route::resource('post', PostController::class);
});
Now, run the laravel 10 to restrict user access from the IP address using the following command.
php artisan serve
You might also like:
- Read Also: Laravel 10 Validate Phone/Mobile Number Example
- Read Also: Laravel 10 User Roles and Permissions Tutorial
- Read Also: Laravel 10 Vue 3 Dependent Dropdown Example
- Read Also: Laravel 10 Get Client IP Address Example