I'm trying to count all the files within a category, and I have these two relationships:
public function files() { return $this->hasMany('App\File', 'category_id','category_id'); } public function fileCount() { return $this->files()->selectRaw("category_id, count(*) AS count") ->groupBy('category_id'); }
This gives me a collection of items, where the count attribute could be accessed like this: $my_category = Category::where("category_id", category_id)->with('fileCount')->get(); $file_counter = $my_category->first()->fileCount->first()->count;
Is it possible to directly attach the count attribute to the $my_category variable? Any suggestions will be appreciated.