I've just watched Adam Wathan's video on Refactoring Loops and Conditionals, and feel like I can use the map collection method in the sumLeagueStats
method on my Team
model (rather than the foreach).
I have a relationship on teams -> leagues, and the getLeagueStats
function gets all of the stats (played, won, drew, lost, for, against, points) from the leagues
table for the relevant team.
In the sumLeagueStats
method I was going to use a foreach
loop and loop through each stat by year, and take the sum of all of the played, etc, and return it, but having watched the above video,
class Team extends Model { public function league() { return $this->hasMany('league'); } public function getLeagueStats($year = [2018]) { return $this->league()->whereIn('year', [$year])->get(); } public function sumLeagueStats($year = [2018]) { foreach { ... return } /* * Want to return a colleciton with the following: * $this->getLeagueStats()->sum('played'); $this->getLeagueStats()->sum('won'); $this->getLeagueStats()->sum('drew'); $this->getLeagueStats()->sum('lost'); $this->getLeagueStats()->sum('for'); $this->getLeagueStats()->sum('against'); $this->getLeagueStats()->sum('points'); */ } }
I'm new to Laravel, so firstly want to check. my suspicions are correct, and secondly looking for any insight/resource for more information, as the docs are slightly lacking).