sesc360's avatar

API Pagination

Hi all,

I want to paginate my json output of an API I wrote. Therefore I use the pagination helpers of laravel.

the index method looks like this:

    public function index()
    {
        $limit = Input::get('limit') ? : 10;
        $incidents = Incident::paginate($limit);

        if( ! $incidents) {
            return Response::json([
                'error' => [
                    'message' => 'There are no incidents in the database.',
                    'code' => 100
                ]
            ], 404);
        } else {
            return $this->respondWithPagination($incidents, [
                'data' => $this->incidentTransformer->transformCollection($incidents->toArray()),
            ]);
        }
    }

And in a separate class APICONTROLLER I have the corresponding method:

 public function respond($data, $headers = []) {
        return Response::json($data, $this->getStatusCode(), $headers);
    }

    public function respondWithPagination(Paginator $incidents, $data)
    {
        return $this->respond([
            $data = array_merge($data, [
                'paginator' => [
                    'total_count'  => $incidents->getTotal(),
                    'total_pages'  => ceil($incidents->getTotal() / $incidents->getPerPage()),
                    'current_page' => $incidents->getCurrentPage(),
                    'limit'        => $incidents->getPerPage()
                ]
            ])
        ]);

        return $this->respond($data);
    }

When I dump the output, I see that there are some results, but then the request crashed with the following error:

ErrorException in IncidentTransformer.php line 10:
Undefined index: incidentReference

This is the IncidentTransformer method:

class IncidentTransformer extends Transformer {
    public function transform($incident) {
        return [
            'incidentReference' => $incident['incidentReference'],
            'latitude' => $incident['latitude'],
            'longitude' => $incident['longitude'],
            'archived' => (boolean) $incident['incidentArchived']
        ];
    }
}

I would guess, that he tries to search for an item that is not available? When I remove all the pagination in the index method, everything is working properly. What did I do wrong?

0 likes
1 reply
taijuten's avatar

The error appears to be saying that $incident['incidentReference'] doesn't exist. Does this match the column from your database correctly?

Also, if you do struggle any further with API transformation and pagination, I'd recommend looking at Fractal http://fractal.thephpleague.com/transformers/.

I'm using this for my API, and the cursor pagination is really useful, especially for large data-sets.

Please or to participate in this conversation.