function topAircraft() { $other = 0; $result = array(); $names = array(); $chart = array(); $counter = $this->query()->select(DB::raw('aircraft_id, count(aircraft_id) as counter'))->groupBy('aircraft_id')->where('aircraft_id', '!=', '')->whereNotNull('aircraft_id')->orderBy('counter', 'DESC')->lists('counter', 'aircraft_id'); if (count($counter) > 0) { $namesRaw = Aircraft::whereIn('code', array_slice(array_keys($counter), 0, 5))->get(); foreach ($namesRaw as $aircraft) { $names[$aircraft->code][] = $aircraft; } $other = $this->_total - array_sum($counter); } foreach ($counter as $key => $flights) { if (count($result) < 5 && array_key_exists($key, $names)) { $percentage = $this->_total == 0 ? 0 : number_format($flights / $this->_total * 100, 1); $result[] = array('data' => $names[$key], 'count' => $flights, 'percent' => $percentage, 'key' => $key); if ($percentage > 0) { $chart[] = [$key, $percentage]; } } else { $other += $flights; } } $result['Other'] = array('count' => $other, 'percent' => $this->_total == 0 ? 0 : number_format($other / $this->_total * 100, 1), 'key' => 'Other'); $chart[] = ['Other', $result['Other']['percent']]; $piechartData = piechartData($chart); return array('table' => $result, 'chart' => $piechartData['javascript'], 'colours' => $piechartData['colours']); }