Home > Net >  Defining an array as an .env variable in laravel 8
Defining an array as an .env variable in laravel 8

Time:10-25

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);
    }
}

CodePudding user response:

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.

CodePudding user response:

It's bad to store array in .env files as it is meant to hold small text values only, storing and array of string, will most likely means this list will grow overtime. but to answer your question there is a hack to get it done.

.ENV file

BLOCK_IP_LIST = "127.0.0.1,127.0.0.2,127.0.0.3"

Now for your Config > app.php file:

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

That should get you up and running, remember to clear your config cache.

CodePudding user response:

you can save your data as json in your .env file

BLOCK_IP_LIST={"127.0.0.1","192.168.1.2"}

and in your controller you can access your data using

$black_lists = json_decode(env('BLOCK_IP_LIST')); 
  • Related