Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel resource not showing "total" attribute inside "meta" when returned as json response

in my Laravel application I created this resource collection using artisan and leave as default:

class QuestionResourceCollection extends ResourceCollection
{
    public function toArray($request)
    {
        return parent::toArray($request);
    }
}

in my controller I’m using the index function to retrieve data from the database and then paginate it using cursor pagination like so:

public function index()
    {
        return new QuestionResourceCollection(Question::query()
            ->with('user')->cursorPaginate(10));
    

the response returned from this contains the links and meta attribute but the meta object does not include the "total" attribute as shown in the docs here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

what am I doing wrong?

>Solution :

You can try per_page and current_page for Cursor Pagination. Instead of total, cursor pagination uses per_page to indicate the number of items per page and current_page to indicate the current page number.
Here is an example.

public function index()
{
    $query = Question::with('user');
    $total = $query->count();
    $perPage = 10;
    $data = new QuestionResourceCollection(
        $query->cursorPaginate($perPage)
    );
    
    return [
        'data' => $data,
        'meta' => [
            'current_page' => $data->currentPage(),
            'per_page' => $perPage,
            'total' => $total,
        ],
    ];
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading