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.
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']);
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',
],
];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With