Search code examples
phplaravel-5phpoffice

Generate PHPExcel Laravel Excel with many to many relations


I am working on an exam/quiz app and it creates tests/quizzes for users and now I must create a set of spreadsheets that contain data such as the present students in a given exam, grades charts and so on.

Bu so far all I managed to create is a sheet with ALL the users using `->fromModel' but if I use any relation and or constrain I get an empty sheet.

I have this models:

 <?php

namespace EMMA5;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Exam extends Model
{
    //

    protected $dates = ['created_at', 'updated_at', 'applicated_at'];

    protected $fillable = [
        'applicated_at',
        'duration',
        'board_id',
        'passing_grade',
        'annotation'
   ];

    public function board()
    {
        return $this->belongsTo('EMMA5\Board');
    }

    public function users()
    {
        return $this->belongsToMany('EMMA5\User')->withPivot('active', 'started_at', 'ended_at', 'seat', 'location_id');
    }

... User model (abbreviated) class User extends Authenticatable { ... //Relations public function answers() { return $this->hasMany(Answer::class); }

    public function exams()
    {
        return $this->belongsToMany('EMMA5\Exam')->withPivot('active', 'started_at', 'ended_at', 'location_id');
    }

...

And I am trying to create a sheet with the users for a given exam: (This is from my ExamController.php)

/**
     * Returns a spreadsheet with only the students that were present
     *
     * @return PHPOffice
     */
    public function gradesSpreadshet(Exam $exam)
    {
            $grade = new Grade;
            $gradedStudents = $grade->allStudents($exam)->toArray();
            //dd(\EMMA5\Exam::find(195)->with('users')->get());
            //dd($exam->answers->answer);
            $data = $exam->users;
            return Excel::create("FinalGrades", function ($excel) use($data) {
                    //Create sheet to be able to return something to keep on testing

                    //Another sheet
                    $excel->sheet('Primera hoja', function ($sheet) use($data) {
                            $sheet->fromArray($data);
                    });
            })->export('xlsx');
    }

And I get an empty sheet. I already tried with ->fromArray() and ->fromModel() . Will appreciate any input.


Solution

  • Some time passed and nobody answered but I found a solution. I do not know if it will be helpful for someone else.

    The way I got the results couldn't be read by Excel Laravel. So I created a helper function with a callback.

    public static function collectionToArray(Array $collect = null) { return array_map(function ($array) use($collect) { foreach ($array as $key => $value) { $resultArray[$key] = $value; } return $resultArray; }, $collect); } This returns a simplified version of the Collection that can be easily read by Excel Laravel.