PHP Laravel 5.8: How to block IP addresses from accessing the application

PHP Laravel 5.8: How to block IP addresses from accessing the application

In this Laravel 5 tutorial, I will let you know how to restrict IP addresses from accessing our application.

Sometime you have annoying visitors or some site scrapers then this example will be helpful to block those users from accessing your website content or apis.

You can restrict bad visitors by IP address or you can allow only specific ip address by creating custom middleware in Laravel application.

Using Laravel middleware you can set the rules on routes for example, you can trim your request data, your can check the authorize the user based on their type etc.

Create Middleware "IpMiddleware"

In this step, I will create a "IpMiddleware" middleware to secure apis or web content.

You can create middleware by running php artisan command:

php artisan make:middleware IpMiddleware

Now I will update the below code in newly created "IpMiddleware" middleware file :

app/Http/Middleware/IpMiddleware.php
<?php
   
namespace App\Http\Middleware;
   
use Closure;
   
class IpMiddleware
{
    
    public $restrictIps = ['103.212.146.23'];
        
    /**
     * 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(['you don't have permission to access this application.']);
        }
    
        return $next($request);
    }
}

Now we need to tell Laravel to run this middleware on routes, so let's register this middleware in Kernel.

app/Http/Kernel.php
protected $routeMiddleware = [   
    ......
    'restrictIp' => \App\Http\Middleware\IpMiddleware::class,
];

Now you can apply this middleware on your routes.

For this example, I have created a api to save user info and I have applied this middleware on it.

Route::middleware(['restrictIp'])->group(function () {
    Route::post('users', 'UserController@saveUserInfo')    
});

Phone: (+91) 8800417876
Noida, 201301