2

Laravel 8 - How to Restrict or Block User Access via IP Address

 1 year ago
source link: https://www.laravelcode.com/post/laravel-8-how-to-restrict-or-block-user-access-via-ip-address
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Laravel 8 - How to Restrict or Block User Access via IP Address

  23192 views

  1 year ago

Laravel

In this article, I will share with you how to Restrict or Block User Access via IP Address in Laravel 8 with example. Many times you need to block some user access on IP address base then here i will share with you a very simple example of how to do it in your laravel application. 

Create Block IP Middleware

First create the middleware in your laravel application using the following artisan command.

php artisan make:middleware RestrictIpAddressMiddleware

app/Http/Middleware/RestrictIpAddressMiddleware.php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class RestrictIpAddressMiddleware
{
    // Blocked IP addresses
    public $restrictedIp = ['192.168.0.1', '202.173.125.72', '192.168.0.3', '202.173.125.71'];

    /**
     * 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->restrictedIp)) {
            return response()->json(['message' => "You are not allowed to access this site."]);
        }
        return $next($request);
    }     
}

Add Middleware in Kernel

now add your created middleware in kernel

app/Http/Kernel.php

protected $middlewareGroups = [
        'web' => [
            ...
            ...
            ...
            
            \App\Http\Middleware\RestrictIpAddressMiddleware::class,
        ],

        'api' => [
            'throttle:api',
            ...
        ],
    ];

i hope you like this solution.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK