【问题标题】:Laravel 9 Rest API - pagination meta tag unavaible when return it with response()Laravel 9 Rest API - 使用 response() 返回时分页元标记不可用
【发布时间】:2022-09-30 14:40:49
【问题描述】:

控制器/Komic 控制器

public function search($value)
   {
       // Query Wildcards and Resources
       $result = new KomikCollection(Komik::where(\'judul\', \'like\', \'%\'. $value .\'%\')->paginate(2));
       return $result;
   }

当我直接返回 $result 时很好

{
\"data\": [],
\"links\": {
\"first\": \"http://localhost:8000/api/komik/a?page=1\",
\"last\": \"http://localhost:8000/api/komik/a?page=2\",
\"prev\": null,
\"next\": \"http://localhost:8000/api/komik/a?page=2\"
},
\"meta\": {
\"current_page\": 1,
\"from\": 1,
\"last_page\": 2,
\"links\": [
{
\"url\": null,
\"label\": \"« Previous\",
\"active\": false
},
{
\"url\": \"http://localhost:8000/api/komik/a?page=1\",
\"label\": \"1\",
\"active\": true
},
{
\"url\": \"http://localhost:8000/api/komik/a?page=2\",
\"label\": \"2\",
\"active\": false
},
{
\"url\": \"http://localhost:8000/api/komik/a?page=2\",
\"label\": \"Next »\",
\"active\": false
}
],
\"path\": \"http://localhost:8000/api/komik/a\",
\"per_page\": 2,
\"to\": 2,
\"total\": 4
}
}

但是当我将使用它返回时助手/响应

    public function search($value)
    {
        // Query Wildcards and Resources
        $result = new KomikCollection(Komik::where(\'judul\', \'like\', \'%\'. $value .\'%\')->paginate(2));

        // send response
        return response()->json($result, 200);
    }

json响应上的元和链接将消失并返回这样的结果

{
\"id\": 1,
\"title\": \"Spare me, Great Lord !\"
},
{
\"id\": 2,
\"title\": \"I\'m An Evil God\"
}

我希望响应包括元和链接标签,我该如何解决这个问题?

    标签: laravel rest


    【解决方案1】:

    如果您想使用响应元数据,那么您必须在收集结果中添加->response()->getData(true)

    所以你的最终功能看起来像:

    public function search($value)
    {
        // Query Wildcards and Resources
        $result = new KomikCollection(Komik::where('judul', 'like', '%'. $value .'%')->paginate(2))->response()->getData(true);
    
        // send response
        return response()->json($result, 200);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-25
      相关资源
      最近更新 更多