Laravel Query get with many-to-many count included
I am setting up a API and looking for an efficient way to return each of my categories with the count of the records in each of the categories.
Because of this post: Laravel hasMany relation count number of likes and comments on post I know that creating an accessor is one possibility, but I'm not sure how to apply an accessor to each record within an object.
Currently I'm using eloquent ::all() to return categories:
public function getAPICategories($localKey){
$data['categories'] = Skill::all();
return Response::json($data)->setCallback('test');
}
This returns the full list of categories in JSONP
/**/test({
"categories":[
{
"id":"1",
"name":"Accounting",
"created_at":"-0001-11-30 00:00:00",
"updated_at":"-0001-11-30 00:00:00",
"deleted_at":null
},
{
"id":"2",
"name":"Advertising",
"created_at":"-0001-11-30 00:00:00",
"updated_at":"-0001-11-30 00:00:00",
"deleted_at":null
}]
});
Specifically, what I'm looking to return: - note added "count":
{
"id":"2",
"name":"Advertising",
**"count":"13",**
"created_at":"-0001-11-30 00:00:00",
"updated_at":"-0001-11-30 00:00:00",
"deleted_at":null
},
The count needs to come from the total number of members with the specific category tag on the contractor_skill pivot table.
Answer
I got the answer I was looking for by building my own array and adding in the data I was looking needed from the eloquent relations:
public function getAPICategories($localKey){
$skills= Skill::all();
$data = [];
foreach ($skills as $skill){
$arr = array(
'id' => $skill->id,
'name' => $skill->name,
'count' => $skill->Contractors->count()
);
$data['categories'][] = $arr;
}
return Response::json($data)->setCallback('test');
}
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS - Conditionally Load a Different Page
- → Make a Laravel collection into angular array (octobercms)
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
- → Validating fileupload(image Dimensions) in Backend Octobercms
- → OctoberCMS Fileupload completely destroys my backend
- → How do I call the value from another backed page form and use it on a component in OctoberCms