How To Restrict User Access From IP Address In Laravel
In Laravel, you can restrict user access from specific IP addresses by creating a middleware that checks the user’s IP address and denies access if it is on a blocked list.
Here are the steps to create a middleware to block access from specific IP addresses:
- Create a new middleware file by running the command
php artisan make:middleware BlockIp
- In the newly created file, add a handle method that retrieves the user’s IP address and compares it to a list of blocked IP addresses.
- Add the middleware to the routes or controllers that you want to block access to.
Here is an example of what the handle method in the middleware file might look like
public function handle($request, Closure $next)
{
$ip = $request->ip();
$blockedIps = ['127.0.0.1', '192.168.0.1'];
if (in_array($ip, $blockedIps)) {
return response()->json(['error' => 'Access denied.'], 403);
}
return $next($request);
}
To add the middleware to a specific route or controller, you can use the middleware
method. For example, if you want to add this middleware to a route group
Route::middleware(['auth','blockip'])->group(function () {
Route::get('/dashboard', 'DashboardController@index');
});
It will block access to the ‘/dashboard’ route for the IP addresses specified in the middleware