In this tutorial you will learn about the Laravel 9 Restrict User Access From IP Address and its application with practical example.
In this Laravel 9 Restrict User Access From IP Address tutorial, I’ll show you how to restrict an IP address from accessing the website using middleware in laravel 9. In this tutorial you will learn to restrict user to access website using IP Address in laravel 9. You will also learn to create custom middleware. With this you will be able to restrict user with specified IP address from accessing the website, In this example we will be creating a middleware to restrict user with IP Address in laravel 9.
Laravel 9 Restrict User Access From IP Address
In this step by step tutorial I will demonstrate you how to restrict from accessing website with IP address. Please follow instruction given below:
- Install Laravel 9
- Connecting App to Database
- Create a Middleware
- Register the Middleware
Install Laravel 9
First of all we need to create a fresh laravel project, download and install Laravel 9 using the below command
1 |
composer create-project --prefer-dist laravel/laravel blog |
Connecting App to Database
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 |
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); } } |
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' => [ //-------------- ], ]; |