D. Coder
D. Coder

Reputation: 57

Laravel Paginated Result Transformation

This is my response Json after I paginate on an eloquent model.

{
    "current_page": 1,
    "data": [
        {
            "title": "First Title",
            "url": "first-title",

        },
        {
            "title": "Second Title",
            "url": "second-title",
        }
    ],
    "first_page_url": "http://xyz.local/api/v1/notifications?page=1",
    "from": 1,
    "last_page": 1,
    "last_page_url": "http://xyz.local/api/v1/notifications?page=1",
    "next_page_url": null,
    "path": "http://xyz.local/api/v1/notifications",
    "per_page": 10,
    "prev_page_url": null,
    "to": 2,
    "total": 2
}

Before returning the response, I want to transform 'url' key from each of the item so I used transform method.

$data = $data->getCollection()->transform(function ($item) {

        $item->url = 'http://xyz.local/'.$item->url;

        return $item;
    });

If I use this transformation and return data, although each items are getting transformed, the other keys like 'current_page', 'next_page_url' are not being returned in the response. If I dont use the transformation, these extra keys are being returned as normal.

Response I am getting after transformation:

{
    [
        {
            "title": "First Title",
            "url": "http://xyz.local/first-title",

        },
        {
            "title": "Second Title",
            "url": "http://xyz.local/second-title",
        }
    ]
}

Response I expect:

{
    "current_page": 1,
    "data": [
        {
            "title": "First Title",
            "url": "http://xyz.local/first-title",

        },
        {
            "title": "Second Title",
            "url": "http://xyz.local/second-title",
        }
    ],
    "first_page_url": "http://xyz.local/api/v1/notifications?page=1",
    "from": 1,
    "last_page": 1,
    "last_page_url": "http://xyz.local/api/v1/notifications?page=1",
    "next_page_url": null,
    "path": "http://xyz.local/api/v1/notifications",
    "per_page": 10,
    "prev_page_url": null,
    "to": 2,
    "total": 2
}

What am I missing here?

Upvotes: 0

Views: 627

Answers (1)

Digvijay
Digvijay

Reputation: 8947

Unlike most other collection methods, transform modifies the collection itself. If you wish to create a new collection instead, use the map method. docs

Either remove the $data = or use $data->getCollection() = $data->getCollection()->map()

Upvotes: 1

Related Questions