如何在Laravel配置中使用变量作为键名?
Hey there! Let's break down why your code is throwing a 500 error and fix it up.
First, I get what you're doing—you can't use Laravel's dot notation for the IP because the dots in the IP would be misinterpreted as config hierarchy levels, so you switched to array access. That makes sense. The problem here is likely trying to access an array key that doesn't exist, which throws a PHP Undefined Array Key error and bubbles up to a 500. When you hardcode the IP, it works because that key is definitely present in your config.
Here are a few solid solutions to fix this:
1. Use Laravel's Arr::get() Helper (Recommended)
This helper is built for safe array access—it'll return null (or a default value you set) instead of throwing an error if the key doesn't exist. Perfect for your use case.
First, make sure you import the helper at the top of your file:
use Illuminate\Support\Arr;
Then adjust your code like this:
$this->clientIp = \Request::ip(); // Grab the full raspberrypis config array first $raspberryConfigs = config('custom.raspberrypis'); // Safely get the 'plant' value for the client IP $location = Arr::get($raspberryConfigs, [$this->clientIp, 'plant']); if ($location) { return response('IP collected', 200); } else { return response('Not Allowed', 401); }
You can also pass a default value as the third argument if you want, like Arr::get($raspberryConfigs, [$this->clientIp, 'plant'], null).
2. Explicitly Check for Key Existence with isset()
If you prefer to stick with raw array access, add checks to make sure the keys exist before accessing them:
$this->clientIp = \Request::ip(); $raspberryConfigs = config('custom')['raspberrypis']; // First check if the IP key exists, then check if 'plant' has a value if (isset($raspberryConfigs[$this->clientIp]) && !empty($raspberryConfigs[$this->clientIp]['plant'])) { return response('IP collected', 200); } else { return response('Not Allowed', 401); }
This prevents PHP from throwing an error when the IP isn't in your config.
Quick Checks to Rule Out Other Issues
- Double-check that your
config/custom.phphas the correct structure. It should look something like this:// config/custom.php return [ 'raspberrypis' => [ '192.168.1.10' => [ 'plant' => 'rose' ], // Other IP entries here ] ]; - Verify that
$this->clientIpdoesn't have any hidden characters (like spaces). You can usetrim($this->clientIp)to clean it up just in case. - Run
dd(config('custom.raspberrypis'))to see all the IPs stored in your config—make sure the client's IP is actually present there.
内容的提问来源于stack exchange,提问作者Roger Creasy

