Laravel控制器向API集合资源传参异常:返回数字而非区域名
问题原因及解决方法
1. 资源类错误访问变量方式
如果区域名是字符串类型,但你在API资源中错误用数组索引方式(比如$this->region[0]),会返回对应位置字符的ASCII码;若直接返回$this->region却得到数字,大概率是传递的变量本身就是数字而非目标字符串。
2. 控制器传递了数组索引而非区域名称
比如读取JSON后得到索引数组,却错误传递了数组的键(索引数字)而非对应值:
// 错误示例:传递了数组索引"0"而非对应名称 $regions = json_decode(file_get_contents(storage_path('regions.json')), true); return PostResource::collection($posts)->each(function ($resource) use ($regions) { $resource->setAttribute('region', array_keys($regions)[0]); });
修正为直接传递数组值:
$resource->setAttribute('region', $regions[0]); // 拿到"Riyadh Region"这类目标值
3. 资源类未正确读取额外传递的参数
如果通过additional()方法传递区域名,资源类不能直接从模型属性中读取(模型无此字段),需从额外参数中获取:
// 错误写法:试图读取模型不存在的region字段,返回默认值或错误关联值 return [ 'id' => $this->id, 'region' => $this->region, ]; // 正确写法:读取额外传递的参数 return [ 'id' => $this->id, 'region' => $this->additional['region'], ];
4. JSON解析未保留关联键名
若JSON是关联数组格式,但解析时未设置json_decode第二个参数为true,会得到对象而非数组,强行访问可能导致错误的数字索引:
// 错误:未转成关联数组,得到对象 $regions = json_decode(file_get_contents(storage_path('regions.json'))); // 正确:解析为关联数组 $regions = json_decode(file_get_contents(storage_path('regions.json')), true);
5. 集合循环时错误使用了索引变量
在资源集合的循环处理中,若误将循环索引($key)赋值给region字段,会返回0、1这类数字:
// 错误示例:把循环索引赋值给region public static function collection($resource) { return new PostCollection($resource->map(function ($item, $key) { $item->region = $key; return $item; })); }
需改为从预加载的区域数据中匹配对应名称。
内容的提问来源于stack exchange,提问作者Alhazmy20
相关产品推荐
相关产品推荐

