In this tutorial you will learn about the How to Restrict or Block User Access via IP Address in Laravel 8 and its application with practical example.
In this How to Restrict or Block User Access via IP Address in Laravel 8 tutorial, I’ll show you how to restrict or block user via IP address from accessing the website in laravel. In this tutorial you will learn to restrict or block user to access website using IP Address in laravel. With this you will be able to restrict or block user via IP address from accessing the website, In this step by step tutorial we will be creating a middleware to restrict user with IP Address in laravel.
How to Restrict or Block User Access via IP Address in Laravel 8
In this step by step tutorial I will demonstrate you with example on how to restrict or block user via IP address from accessing the website in laravel. Please follow the instruction given below:
Create Laravel Application
First of all we need to create a fresh laravel project, download and install Laravel 8 using the below command
1 |
composer create-project laravel/laravel laravel-block-ip-address-example --prefer-dist |
Database Connection
Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.
1 2 3 4 5 6 |
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=db DB_USERNAME=root DB_PASSWORD= |
Create Block IP Middleware
In this step we will create a custom middleware to restrict users via ip address. Run following command to create a middleware named class BlockIpMiddleware:
1 |
php artisan make:middleware RestrictIpAddressMiddleware |
Then, go to app/Http/Middleware/RestrictIpAddressMiddleware.php configuration file and replace the entire code with the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?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, we have to define the RestrictIpAddressMiddleware class in the $middlewareGroups array within the app/Http/Kernel.php file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
protected $middlewareGroups = [ 'web' => [ ... ... ... \App\Http\Middleware\RestrictIpAddressMiddleware::class, ], 'api' => [ 'throttle:api', ... ], ]; |