Search code examples
octobercmsoctobercms-plugins

How to Using Pagination in oc-api-plugin?


octobercms plugin: oc-api-plugin

I don't know what's missing

I've been trying for a while with no success using API Using Pagination

Below is the program I built

routes.php

<?php
Route::group([
    'prefix'    => 'api/v1/sample',
    'namespace' => 'Sh\Sample\Controllers',
], function () {

        Route::get('posts', 'postsAPI@index');
        Route::get('posts/{id}', 'postsAPI@show');
});

PostTransformer.php

<?php

namespace Sh\Sample\Transformers;
use Octobro\API\Classes\Transformer;
use Sh\Sample\Models\Post;

class PostTransformer extends Transformer
{
    // Related transformer that can be included
    public $availableIncludes = [
        //'entities'
    ];

    // Related transformer that will be included by default
    public $defaultIncludes = [
        //'entities',
    ];

    public function data(Post $item)
    {
        return [
            'id' => (int)$item->id,
            'title' => $item->title,
            'content' => $item->content
        ];
       
    }
}

PostsAPI.php

<?php namespace Sh\Sample\Controllers;

use Sh\Sample\Models\Post;
use Octobro\API\Classes\ApiController;
use Sh\Sample\Transformers\PostTransformer;

class PostsAPI extends ApiController
{
    public function index()
    {
        $item = Post::get();
        return $this->respondwithCollection($item, new PostTransformer);
    }

    public function show(int $id)
    {
        $item = Post::find($id);
        return $this->respondwithItem($item, new PostTransformer);
    }

}

TEST:

GET: http://127.0.0.1/api/v1/sample/posts

{
    "data": [
        {
            "id": 1,
            "title": "test11",
            "content": "teste222"
        },
        {
            "id": 2,
            "title": "test222",
            "content": "test222222"
        },
        {
            "id": 3,
            "title": "test333",
            "content": "content333"
        },
        {
            "id": 4,
            "title": "test333",
            "content": "test333"
        }
    ]
}

Using Paginator not working

GET: http://127.0.0.1/api/v1/sample/posts?page=1,number=2


Solution

  • You need to use respondWithPaginator method to use pagination.

    Ref: Pagination in oc-api-plugin

    class PostsAPI extends ApiController
    {
        public function index()
        {
            $postPaginator = Post::paginate();
            return $this->respondWithPaginator($postPaginator, new PostTransformer);
        }
    

    if any doubt please comment.