Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add meta data in laravel api resource

Tags:

php

laravel

I using laravel api resource for my FRONT-END site.

Actually i using also laravel pagination to handle paginate in FRONT-END.

The api resource structure like this:

{
    "data": [...],
    "links": [...], // handle pagination
    "meta": [...] // handle pagination
}

But i want to send count of query results without considering paginating .For example i paginating database result into 30 pre_page and the all of query result is 200 and i want to send this count to view front-end

I decided to get count of query result and give to resource collection and restructure laravel api resource to this.

{
    "data": [...],
    "metadata": {
        "count": 200
    },
    "links": [...], // handle pagination
    "meta": [...] // handle pagination
}

Also you sould know maybe i want to add another data to this collection. for example conversion rate in addition count to metadata and i don't know how do this.

like image 826
mohammad13 Avatar asked Oct 12 '25 08:10

mohammad13


2 Answers

I find the way hou can i do this

Actually i just have to use additional method for laravel resource like:

$data = Project::limit(100)->get();
return ProjectResource::collection($data)->additional(['some_id => 1']);
like image 196
mohammad13 Avatar answered Oct 14 '25 20:10

mohammad13


See top-level-meta-data.

You need to create a ResourceCollection and then define the additional meta variables in the with function.

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\ResourceCollection;

class UserCollection extends ResourceCollection
{
    /**
    * Transform the resource collection into an array.
    *
    * @param  \Illuminate\Http\Request  $request
    * @return array
    */
    public function toArray($request)
    {
        return parent::toArray($request);
    }

    /**
    * Get additional data that should be returned with the resource array.
    *
    * @param  \Illuminate\Http\Request  $request
    * @return array
    */
    public function with($request)
    {
        return [
            'meta' => [
                'key' => 'value',
            ],
        ];
    }
}
like image 22
Holyboly Avatar answered Oct 14 '25 21:10

Holyboly