Laravel Query get with many-to-many count included

- 1 answer

Ad

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.

Ad

Answer

Ad

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');
}
Ad
source: stackoverflow.com
Ad