Block IP address from accessing Laravel application

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.

How to block or restrict any IP address from accessing your Laravel application ? lets see. We can create a Middleware to check the blocked IP address and redirect to the page we want.

  1. Create a Middleware “RestrictIpMiddleware.php”.
  2. Paste the code inside handle function.
  3. Register the middleware in kernel function.
  4. Add the registered middleware in routes in order to restrict the access.

Creating a Middleware

php artisan make:middleware RestrictIpMiddleware

The Code

Paste the below code in the handle function of the middleware


 $restricted_ip = "Comma seperated IP address which is to be restricted"; 
 $ipsDeny = explode(',',preg_replace('/\s+/', '', $restricted_ip));
 if(count($ipsDeny) >= 1 )
 {
    if(in_array(request()->ip(), $ipsDeny))
    {
        \Log::warning("Unauthorized access, IP address was => ".request()->ip);
         return response()->json(['Unauthorized!'],400);
    }
 }
 return $next($request);

Install Laravel Valet in Ubuntu

The official Laravel Valet development environment is great if you are an Apple user and thanks to Carlos Priego you can now enjoy the same benefits you are an Ubuntu user.

Lets see how to install Valet in Ubuntu 16.04 LTS.
Installation is really simple. First, make sure you are running Ubuntu >= 15.04 with PHP >= 5.6.
1. Now you’ll need the following dependencies and packages:

sudo apt-get install libnss3-tools jq xsel

2. PHP Packages (replace the * with your PHP version):

php*-cli php*-common php*-curl php*-json php*-mbstring php*-mcrypt php*-opcache php*-readline php*-xml php*-zip

3. The final step

composer global require cpriego/valet-ubuntu
valet install

That’s all. Cheeeers 😉 You have Valet in your machine. Enjoy 🙂