Skip to content

Paginator object formatting #19

Closed
Closed
@terion-name

Description

@terion-name

I don't make a pull request because this enhancement should be thought over, but I think that this have sense to be implemented.
Here is my "peace of code" from controller, that normalizes Paginator object to json api format:

if ($response instanceof \Illuminate\Pagination\Paginator) {
    $items = $response->getCollection();
    $itemsKey = 'items';
    $return = [];
    if ($items->count() > 0 && ($firstItem = $items->get(0)) instanceof \Illuminate\Database\Eloquent\Model) {
        $itemsKey = $firstItem->getTable();
    }
    $meta = [
        'total' => $response->getTotal(),
        'per_page' => $response->getPerPage(),
        'current_page' => $response->getCurrentPage(),
        'last_page' => $response->getLastPage(),
        'from' => $response->getFrom(),
        'to' => $response->getTo()
    ];
    if ($items->count() > 0) {
        $return[$itemsKey] = $items;
    }
    $return['meta'] = $meta;
    return $return;
}

This will result in output:

{"users": [
    {
        "_id": "535fa16f6e6c631f936cb2a1",
        "name": "Foo"
    },
    {
        "_id": "535fa16f6e6c631f936cb2a2",
        "name": "Bar"
    }
], "meta": {
    "total": 2,
    "per_page": 10,
    "current_page": 1,
    "last_page": 1,
    "from": 1,
    "to": 2
}}

What do you think about implementation of this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions