Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel paginate resources won't add meta

Tags:

php

laravel

I have resources data returning in JSON. When I try to get my data with paginate it is not included meta data.

Based on documentation my data supposed to be included meta like:

"meta":{
    "current_page": 1,
    "from": 1,
    "last_page": 1,
    "path": "http://example.com/pagination",
    "per_page": 15,
    "to": 10,
    "total": 10
}

but my data is returning like this:

one

Code

controller

public function index()
{
    $products = ProductFrontResource::collection(Product::orderby('id', 'desc')->with(['photos', 'seo', 'tags', 'variations', 'variations.children', 'options', 'options.children', 'categories'])->where('active', 'yes')->paginate(8));
    return response()->json([
        'data' => $products,
        'message' => 'Products retrieved successfully.',
    ]);
}

Any idea?

like image 797
mafortis Avatar asked Oct 27 '25 05:10

mafortis


1 Answers

You don't need to use response(). Laravel's resource classes allow you to expressively and easily transform your models and model collections into JSON.

Every resource class defines a toArray method which returns the array of attributes that should be converted to JSON when sending the response.

public function index()
{
    $data = Product::orderby('id', 'desc')
        ->with(['photos', 'seo', 'tags', 'variations', 'variations.children', 'options', 'options.children', 'categories'])
        ->where('active', 'yes')
        ->paginate(8);

    $products = ProductFrontResource::collection($data);

    return $products;
}

Additional Meta Data

'message' => 'Products retrieved successfully.'

Yes, you can Adding Meta Data.

public function toArray($request)
{
    return [
        'data' => $this->collection,
        'message' => 'Products retrieved successfully.'
    ];
}
like image 93
Wahyu Kristianto Avatar answered Oct 28 '25 17:10

Wahyu Kristianto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!