In this tutorial you will learn about the Laravel 7 Restrict IP Address From Accessing Website and its application with practical example.
In this Laravel 7 Restrict IP Address From Accessing Website tutorial, I’ll show you how to restrict an IP address from accessing the website in laravel. In this tutorial you will learn to restrict user to access website using IP Address in laravel. With this you will be able to restrict user with specified 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.
Laravel 7 Restrict IP Address From Accessing Website
- Download Laravel Setup
- Configure .env file
- Create a Middleware
- Register the Middleware
Step 1: Download Laravel Setup
First of all we need to create a fresh laravel project, download and install Laravel using the below command
1 |
composer create-project --prefer-dist laravel/laravel blog |
Step 2: Configure .env file
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=here your database name here DB_USERNAME=here database username here DB_PASSWORD=here database password here |
Step 3: Create a Middleware
Next step, Run the following artisan command to create a middleware named class BlockIpMiddleware:
1 |
php artisan make:middleware BlockIpMiddleware |
Now, Go to app/Http/Middleware folder and open BlockIpMiddleware.php file. Then put the following code in BlockIpMiddleware.php file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php namespace App\Http\Middleware; use Closure; class BlockIpMiddleware { // set IP addresses public $blockIps = ['ip-addr-1', 'ip-addr-2', '127.0.0.1']; /** * 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->blockIps)) { return response()->json(['message' => "You don't have permission to access this website."]); } return $next($request); } } |
Step 4: Register the Middleware
Now, we need to register the middleware, so go to app/Http/ and open Kernel.php file. And register middleware as follow:
1 2 3 4 5 6 7 8 9 |
protected $middlewareGroups = [ 'web' => [ //-------------- \App\Http\Middleware\BlockIpMiddleware::class, ], 'api' => [ //-------------- ], ]; |