Is there a way to append a count of objects in a nested collection as an attribute in laravel?
Solution 1:
There are a few ways to do this, so I will provide one possible solution.
You can look into Laravel Accessors - https://laravel.com/docs/8.x/eloquent-mutators#defining-an-accessor
In your case, you could have functions on your Match model like so:
public function getGoalsTeamAAttribute() {
// calculate and return goal count for team A
}
public function getGoalsTeamBAttribute() {
// calculate and return goal count for team B
}
public function getResultAttribute() {
// calculate and return result
}
You can then do one of two things to include this data on the collection.
-
Add
$appends = ['result', 'goals_team_a', 'goals_team_b'];
to the top of your Match model. This will append these values onto the collection when you cast it to an array or to JSON. Google 'laravel appends' for more info. -
When you have a Match as an eloquent object, simply call
$match->goals_team_a
and it will do the calculation on the fly. You would want to be careful of n+1 problems with this approach, since it will run any database queries that are in yourgetGoalsTeamAAttribute
function. You would want to make sure you're lazy loading (->with('goals')
) before running$match->goals_team_a
.