Restrict User Access from IP Address in Laravel 9 Tutorial

Today, We are going to learn how to Restrict User Access from IP Address in Laravel 9 Tutorial. In this tutorial you learn how you can restrict certain user IP to access your site and show then the restrict message.

We are going to use middleware to block or restrict the user access from IP address in laravel 9 application. So let begin our tutorial with the following steps.

Steps to Restrict User Access from IP Address in Laravel 9 Tutorial:

  • Step 1: Installing fresh new Laravel 9 Application
  • Step 2: Creating Middleware
  • Step 3: Registering Middleware
  • Step 4: Using Middleware
  • Step 5: Testing
  • Step 6: Conclusion

Also Read: Create React JS CRUD using Vite in Laravel 9 Example

Step 1: Installing fresh new Laravel 9 Application

First step, We are going to install a fresh new laravel 9 application. To install a laravel application run the following command in terminal.

composer create-project laravel/laravel laraveltuts-app

cd laraveltuts-app

Note: laraveltuts-app” is a laravel application name.

Step 2: Creating Middleware

Now, Next step is to create a BlockIpMiddleware middleware. To create a middleware run the following command in terminal.

php artisan make:middleware BlockIpMiddleware

This command will create a new file BlockIpMiddleware.php under app/Http/Middleware/ folder. Update the following of the file as shown below.

<?php
  
namespace App\Http\Middleware;
  
use Closure;
use Illuminate\Http\Request;
  
class BlockIpMiddleware
{
    public $blockIps = ['whitelist-ip-1', 'whitelist-ip-2', '127.0.0.1'];
  
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if (in_array($request->ip(), $this->blockIps)) {
            abort(403, "You are restricted to access the site.");
        }
  
        return $next($request);
    }
}

Also Read: How to Store JSON in Database Laravel 9

Step 3: Registering Middleware

Now, We need to register the middleware which we just created to Kernel.php. So let’s update following file.

app/Http/Kernel.php

<?php
  
namespace App\Http;
  
use Illuminate\Foundation\Http\Kernel as HttpKernel;
  
class Kernel extends HttpKernel
{
    ....
  
    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        ....
        'blockIP' => \App\Http\Middleware\BlockIpMiddleware::class,
    ];
}

Step 4: Using Middleware

In this step, We are using our blockIP middleware to block or restrict the route. So, this route did not access to the page. This will show a restricting page error! so let’s open your route file and update following code:

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\RSSFeedController;
use App\Http\Controllers\UserController;
   
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

/* Route No Access to visitors */
Route::middleware(['blockIP'])->group(function () {
    Route::get('/dashboard', function () {
        return view('welcome');
    });
});

/* Route Access to visitors */
Route::get('/home', function () {
    return view('welcome');
});

Also Read: Enum Model Attribute Casting in Laravel 9 Example

Step 5: Testing

So, Everything is done! we can now test our laravel application. Run the following command to start the laravel server.

php artisan serve

and try to open the following URL in any web browser.

http://127.0.0.1:8000/dashboard //Blocked URL Route

http://127.0.0.1:8000/home //Not Blocked URL Route

This will show the following result:

Restrict User Access from IP Address in Laravel 9 Tutorial
Restrict User Access from IP Address in Laravel 9

Step 6: Conclusion

Today, We had learn Restrict User Access from IP Address in Laravel 9 Tutorial. Hope this tutorial helped you with learning Laravel 9. If you have any question you can ask us at comment section below. If you like the tutorial please subscribe our YouTube Channel and follow us on social network Facebook and Instagram.

Also Read: Livewire Pagination Laravel 9 Example Tutorial

4 Comments

Leave a Reply