Skip to content
Advertisement

Paginating with laravel collection in api

I got problem in Laravel Api collection paginate.

I have categories and I need to bring all products that belongs to a single category

My code:

public function show($id)
{
    $category = Category::find($id);
    if($category){
        return  new ProductCollection($category->products->paginate(10));
    }
}

The code of paginate in AppServiceProvider at boot method

Collection::macro('paginate', function($perPage, $total = null, $page = null, $pageName = 'page') {
        $page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);

        return new LengthAwarePaginator(
            $this->forPage($page, $perPage),
            $total ?: $this->count(),
            $perPage,
            $page,
            [
                'path' => LengthAwarePaginator::resolveCurrentPath(),
                'pageName' => $pageName,
            ]
        );
 });

The result in first page is fine:

"data": [
    {
        "id": 6674,
        "name": "test",
    },
    {
        "id": 6668,
        "name": "test2"
    },

],
"links": {
    "first": "http://example.test/api/auth/categories/2176?page=1",
    "last": "http://example.test/api/auth/categories/2176?page=5",
    "prev": null,
    "next": "http://example.test/api/auth/categories/2176?page=2"
},
"meta": {
    "current_page": 1,
    "from": 1,
    "last_page": 5,
    "path": "http://example.test/api/auth/categories/2176",
    "per_page": 10,
    "to": 10,
    "total": 43
}

The problem in the second page( the number key of the data( 10 , 11 ) before each product i need to remove it!

"data": {
    "10": {
        "id": 6613,
        "name": "test3",
    },
    "11": {
        "id": 6601,
        "name": "test4",
    },
},
"links": {
    "first": "http://example.test/api/auth/categories/2176?page=1",
    "last": "http://example.test/api/auth/categories/2176?page=5",
    "prev": "http://example.test/api/auth/categories/2176?page=1",
    "next": "http://example.test/api/auth/categories/2176?page=3"
},
"meta": {
    "current_page": 2,
    "from": 11,
    "last_page": 5,
    "path": "http://example.test/api/auth/categories/2176",
    "per_page": 10,
    "to": 20,
    "total": 43
}

Advertisement

Answer

You can try pagination in eloquent resources, so instead of creating custom paginate, you can do like this:

return  new ProductCollection($category->products()->paginate(10));
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement