jeudi 3 août 2017

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 `->fromArray' 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.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2vmpfEm
via IFTTT

Aucun commentaire:

Enregistrer un commentaire