Search code examples
laravelrest

Laravel 9 Rest API - pagination meta tag unavaible when return it with response()


Controllers/Komic Controller

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

its fine when i directly return the $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
}
}

but when i'll return it using helpers/response

    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);
    }

the meta and link on the json response will be disapppear and return result like this

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

I want the response include the meta and link tags, how do i fix this?


Solution

  • If you want to meta data with response then you must need to add ->response()->getData(true) in collection results.

    So your final function looks like :

    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);
    }