Search code examples
phplaravelenvironment-variableslaravel-8laravel-middleware

Defining an array as an .env variable in laravel 8


I have an array that I pull data from.

BLOCK_IP_LIST = [127.0.0.1,127.0.0.2,127.0.0.3]

I'm not sure how to do that.

I have Use .env BLOCK_IP_LIST in BlockIpMiddleware using Config>app.php

Config.app.php code like

'block_ip' => env('BLOCK_IP_LIST'),

my BlockIpMiddleware Code Like

class BlockIpMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        $blockIps = config('app.block_ip');

        if (in_array($request->ip(), $blockIps)) {
            return response()->json(['message' => "You don't have permission to access this website."]);
        }
        return $next($request);
    }
}

Solution

  • Your BlockIpMiddleware is alright

    but .env should look like that

    BLOCK_IP_LIST=127.0.0.1,127.0.0.2,127.0.0.3
    

    Inside app.php

    'block_ip' => explode(',', env('BLOCK_IP_LIST')),
    

    explode find , and convert from string to array.


    My opinion

    You should do it with the database and cache it forever Because you/client can add/delete the IPs as you want and anytime.