You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel资源集合报错:Undefined property: Illuminate\Database\Query\Builder::$map

解决Laravel Resource Collection报错"Undefined property: Illuminate\Database\Query\Builder::$map"

以下是针对性的排查和修复步骤:

1. 确认Resource Collection的继承关系

确保你的UserCollection正确继承自Illuminate\Http\Resources\Json\ResourceCollection,而非单个资源的Resource类:

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\ResourceCollection;
use App\Http\Resources\UserResource;

class UserCollection extends ResourceCollection
{
    // 可选但推荐:指定集合中每个元素对应的单个资源
    protected $collects = UserResource::class;

    public function toArray($request)
    {
        return [
            'data' => $this->collection,
            // 可添加自定义字段如总数、分页信息
            'total' => $this->collection->count()
        ];
    }
}

2. 控制器传入正确的集合实例

在UserController的index方法中,必须传给UserCollection执行后的查询结果集合,不能直接传入Query Builder实例:

// 错误写法:传入未执行的查询构建器
// return new UserCollection(User::query());

// 正确写法:先执行查询得到集合
return new UserCollection(User::get());

// 分页场景的正确写法:
// return new UserCollection(User::paginate(15));

3. 避免不必要的响应嵌套

不要将UserCollection包裹在额外的数组或response()->json()中,因为Resource Collection本身已生成规范的JSON结构:

// 错误写法:额外嵌套导致处理异常
// return response()->json([
//     'data' => new UserCollection(User::get())
// ]);

// 正确写法:直接返回Resource Collection实例
return new UserCollection(User::get());

4. 验证单个资源的可用性

如果UserCollection指定了$collects属性,确认对应的UserResource能正常工作(你的show方法已验证此点,此步可快速确认):

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class UserResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            // 其他业务字段
        ];
    }
}

内容的提问来源于stack exchange,提问作者Maik Lowrey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 05:30:52