Laravel Block IP Addresses from Accessing Website

Admin   Laravel   106  2021-03-16 04:20:10

Hi Guys,

In this artical,I will learn you how to access particular ip address laravel application.you can simply check to restrict ip address in laravel.

In many cases we need to block some particular IP address from accessing our website content or application. We can restrict IP in Laravel through a simple piece of code.

Create a Middleware

you can run this command in your terminal.

  

php artisan make:middleware CheckIpMiddleware

app/Http/Middleware/CheckIpMiddleware

 

<?php

namespace App\Http\Middleware;

use Closure;

class CheckIpMiddleware

{

// set IP addresses

public $restrictIps = ['ip-addr-0', 'ip-addr-1', '127.0.0.5'];

/**

* 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->restrictIps)) {

return response()->json(['message' => "You don't valid Ip Address"]);

}

return $next($request);

}

}

app/Http/Middleware/Kernel.php

 

protected $middlewareGroups = [

'web' => [

//--------------

\App\Http\Middleware\CheckIpMiddleware::class,

],

'api' => [

//--------------

],

];

Test

you can run to this particular Ip address then display message in your browser.

 

You don't valid Ip Address

It will help you...