/** * Export the referrals and the related newcomers into a CSV file. * * @return string */ public function getExportReferrals() { $referrals = Student::select([\DB::raw('students.first_name'), \DB::raw('students.last_name')])->orderBy('last_name')->rightjoin('newcomers as n', 'students.student_id', '=', 'n.referral_id')->addSelect([\DB::raw('n.branch as branch'), \DB::raw('n.first_name as newcomer_first_name'), \DB::raw('n.last_name as newcomer_last_name'), \DB::raw('n.phone as newcomer_phone')])->get(); return Excel::create('Referrals', function ($file) use($referrals) { $file->sheet('', function ($sheet) use($referrals) { $sheet->fromArray($referrals); }); })->export('csv'); $referrals = Referral::orderBy('last_name')->where('validated', 1)->get(); // Embed the referral's newcomers in the document. foreach ($referrals as &$referral) { for ($i = 0; $i < $referral->newcomers()->count(); $i++) { $newcomer = $referral->newcomers()->get()->toArray()[$i]; $referral['Fillot ' . $i] = $newcomer['first_name'] . ' ' . $newcomer['last_name']; } } return Excel::create('Parrains', function ($file) use($referrals) { $file->sheet('', function ($sheet) use($referrals) { $sheet->fromArray($referrals); }); })->export('csv'); }