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

Laravel自定义JSON响应函数返回API资源时缺失分页链接如何解决

Laravel 自定义响应丢失分页元数据解决方案

问题原因

直接返回PostResource::collection(分页实例)时,Laravel 会自动将分页器附带的元数据(总条数、上下页链接、当前页等)与数据集合并输出。但直接将资源集合实例作为普通参数传入自定义响应函数时,JSON 序列化只会读取集合内的业务数据,不会主动携带分页相关的元数据,因此会出现分页信息丢失的问题。

解决方案

有两种可选的修复方式,按需选择即可:

方案1:修改业务代码,提前转换资源集合结构

将你原来业务代码中$response的赋值逻辑修改为如下内容:

try {
    $type = 'success';
    $status_code = 200;
    $message = 'Posts data listed.';
    // 先获取分页实例
    $paginator = Post::with(['associate:id,name,avatar', 'comments:id,commenter_id,commentable_id,comment,created_at'])
        ->latest('posts.created_at')
        ->paginate(2);
    // 调用response()->getData(true) 得到包含data、links、meta的完整数组
    $response = PostResource::collection($paginator)->response()->getData(true);
} catch (Exception $e) {
    $type = 'error';
    $status_code = $e->getCode();
    $message = $e->getMessage();
    $response = false;
}
return response_data($type, $status_code, $message, $response);

方案2:修改自定义响应函数,自动识别处理资源集合

如果不想每次写资源集合都手动转换,可以统一修改response_data函数,增加自动识别逻辑,原有业务代码无需改动:

function response_data($type, $status, $message = false, $response)
{
    // 新增判断:如果传入的是资源集合实例,自动转换为带分页元数据的完整数组
    if ($response instanceof \Illuminate\Http\Resources\Json\ResourceCollection) {
        $response = $response->response()->getData(true);
    }
    return response()->json([
        'type' => $type,
        'status' => $status,
        'message' => $message,
        'response' => $response
    ]);
}

修改完成后返回的响应结构会自动包含分页信息,示例如下:

{
    "type": "success",
    "status": 200,
    "message": "Posts data listed.",
    "response": {
        "data": [/* 原有业务数据集 */],
        "links": {
            "first": "请求地址?page=1",
            "last": "请求地址?page=总页数",
            "prev": "上一页地址",
            "next": "下一页地址"
        },
        "meta": {
            "current_page": 1,
            "from": 1,
            "last_page": 总页数,
            "per_page": 2,
            "total": 数据总条数
            // 其他分页元数据
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 11:54:04