люмен 6: как реструктурировать данные ответной нумерации страниц на люмен? - PullRequest
1 голос
/ 09 марта 2020

Я потратил много времени, чтобы решить эту проблему. Как мне реструктурировать данные ответа json Пагинация с просветом? что я должен использовать между ресурсами API и трансформатором? Подсветка пагинации?

Мой PersonController, который я пытаюсь использовать LengthAwarePagination

use App\Model\Person;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;

public function index(Request $request)
{

    $results = Person::all();

    $data = array();

    $currentPage = LengthAwarePaginator::resolveCurrentPage();

    $collection = new Collection($results);

    $per_page = 1;

    $currentPageResults = $collection->slice(($currentPage-1) * $per_page, $per_page)->all();

    $data = new LengthAwarePaginator($currentPageResults, count($collection), $per_page);

    $data->setPath($request->url());

    return $data;
}

Фактический ответ

{
    "current_page": 1,
    "data": [
        {
           "id": 1,
           "type": "persons",
           "attributes": {
              "name": "andrew",
              "country": "new zealand",
              "gender": "male"
            },
        }
    ],
    "first_page_url": "http://localhost:8000/person?page=1",
    "from": 1,
    "last_page": 50,
    "last_page_url": "http://localhost:8000/person?page=50",
    "next_page_url": "http://localhost:8000/person?page=2",
    "path": "http://localhost:8000/person",
    "per_page": 1,
    "prev_page_url": null,
    "to": 1,
    "total": 50
}

, но ожидаемый ответ

{
    "meta": {
       "count": 5,
       "total": 20
    },
    "links": {
        "first": "http:localhost:8000/api/v1/persons?page[limit]=10&page[offset]=0",
        "last": "http:localhost:8000/api/v1/persons?page[limit]=10&page[offset]=10",
        "next": "http:localhost:8000/api/v1/persons?page[limit]=10&page[offset]=10",
        "prev": "null"
    },
    "data": [
       {
         "type": "persons",
         "id": "1",
         "attributes": {
             "name": "andrew",
             "country": "new zealand",
             "gender": "male"
         },
         "links": {
            "self": "http:localhost:8000/api/v1/persons/1/"
         }
       }
    ]
}

Что мне делать?

1 Ответ

0 голосов
/ 09 марта 2020

Это на самом деле довольно просто.

Вместо возврата $data вы можете вернуть что-то вроде этого:

    return response()->json([
        'meta' => [
            "count" => count($collection),
            "total" => $data->total
        ],
        'links' => [
            "first" => $data->first_page_url,
            "last" => $data->last_page_url,
            "next" => $data->next_page_url,
            "prev" => $data->prev_page_url
        ],
        'data' => $data->data
    ]);
...