修复后台 /admin/game-reward-logs 页面报错问题,错误信息为:TypeError: "json_decode(): Argument #1 ($json) must be of type string, array given"
kku_game_reward_logs 表的 reward_items 字段存储的是JSON格式数据GameRewardLog 模型中设置了 'reward_items' => 'json' 的castjson_decode() 尝试解码已经是数组的数据app/Module/Game/AdminControllers/GameRewardLogController.php 第51行(列表页面)app/Module/Game/AdminControllers/GameRewardLogController.php 第106行(详情页面)列表页面修复(第50-58行):
// 修复前
$grid->column('reward_items', '奖励项')->display(function ($items) {
$items = json_decode($items, true); // 错误:重复解码
// ...
});
// 修复后
$grid->column('reward_items', '奖励项')->display(function ($items) {
// 由于模型中已设置了json cast,$items已经是数组,无需再次json_decode
// ...
});
详情页面修复(第103-129行):
// 修复前
$show->field('奖励项')->as(function () {
$items = json_decode($this->reward_items, true); // 错误:重复解码
// ...
});
// 修复后
$show->field('奖励项')->as(function () {
// 由于模型中已设置了json cast,reward_items已经是数组,无需再次json_decode
$items = $this->reward_items;
// ...
});
http://kku_laravel.local.gd/admin/game-reward-logs测试记录ID 4413的详情页面:
'field' => 'json' cast时json_decode()-- reward_items字段存储JSON格式数据
SELECT reward_items FROM kku_game_reward_logs LIMIT 1;
-- 结果示例:
[
{
"id": 76,
"param1": 0,
"param2": 0,
"quantity": 1,
"target_id": 3,
"extra_data": null,
"reward_type": 9
}
]
app/Module/Game/AdminControllers/GameRewardLogController.php - 主要修复文件app/Module/Game/Models/GameRewardLog.php - 模型定义(包含JSON cast配置)app/Module/Game/Repositorys/GameRewardLogRepository.php - 数据仓库app/Module/Game/Enums/REWARD_TYPE.php - 奖励类型枚举app/Module/Game/Enums/REWARD_SOURCE_TYPE.php - 奖励来源类型枚举修复游戏奖励日志后台页面json_decode错误
- 修复GameRewardLogController中reward_items字段的json_decode错误
- 由于模型中已设置json cast,reward_items已经是数组,无需再次json_decode
- 修复列表页面和详情页面的显示问题
- 测试确认页面正常显示奖励项信息
此次修复解决了Laravel模型JSON cast机制与手动JSON解码冲突的问题。当模型中已经设置了JSON cast时,字段会自动转换为相应的PHP类型,无需在控制器中再次进行类型转换。这是一个常见的Laravel开发陷阱,需要注意模型cast配置与控制器逻辑的一致性。