Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

DInu98's avatar

how to export Laravel Excel Export with HasMany Relationship?

I tried to export data to excel using this method but it doesn't work. there is getting error.

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\Exportable;

Use App\Models\Student;
Use App\Models\Course;


class StudentExport implements FromQuery,WithMapping,WithHeadings
{
    use Exportable;

    protected $selected;

    public function __construct($selected)
    {
        $this->selected = $selected;
    }
    /**
    * @return \Illuminate\Support\Collection
    */
    public function headings(): array
    {
        return[
            'Student ID',
            'Student Full Name',
            'Contact',
            'Contact Whatsaap',
            'School',
            'Address',
            'Enroll Courses',
            'Registered Date',
        ];
    }

    public function map($student): array
    {
         return[
             $student->student_id,
             $student->FullName,
             $student->email,
             $student->contact,
             $student->contact_whatsapp,
             $student->school,
             $student->address,
             $student->courses->Name,
             $payment->created_at->toDatestring(),
         ];
    }

    public function query()
    { 
        return Student::with('Course:id,Name')->whereIn('id',$this->selected);
    }
}

Student Model

 public function courses()
    {
        return $this->belongsToMany(Course::class,'course_student');
    }

Course Model

 public function students()
    {
        return $this->belongsToMany(Student::class,'course_student');
    }

controller

 //export reports 
    public function export()
    {
        return (new StudentExport ($this->selected))->download('students-detials.xls'); 
      
    }
0 likes
8 replies
Nakov's avatar

And will it work if you add comma separated list of courses the user has been enrolled in?

$student->courses->pluck('Name')->implode(', '),
2 likes
DInu98's avatar

@Nakov hello, no its not worked.. i getting error like this

Call to undefined relationship [Course] on model [App\Models\Student].
Nakov's avatar

@DInu98 That's an error that comes from this code I believe:

return Student::with('Course:id,Name')->whereIn('id',$this->selected);

so change it to this:

return Student::with('courses:id,Name')->whereIn('id',$this->selected);

and it would've been better if you used lower case for your column names.

1 like
DInu98's avatar

@Nakov hello, thank you for helping me, I have many to many relationship. also i have pivot table name called course_student. i tried that above method that you mentioned but unfortunately getting error like this. i want to get students details with enrolled courses names

Undefined property: Illuminate\Database\Eloquent\Relations\BelongsToMany::$Name
namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\Exportable;

Use App\Models\Student;
Use App\Models\Course;


class StudentExport implements FromQuery,WithMapping,WithHeadings
{
    use Exportable;

    protected $selected;

    public function __construct($selected)
    {
        $this->selected = $selected;
    }
    /**
    * @return \Illuminate\Support\Collection
    */
    public function headings(): array
    {
        return[
            'Student ID',
            'Student Full Name',
            'Contact',
            'Contact Whatsaap',
            'School',
            'Address',
            'Enroll Courses',
            'Registered Date',
        ];
    }

    public function map($student): array
    {
         return[
             $student->student_id,
             $student->FullName,
             $student->email,
             $student->contact,
             $student->contact_whatsapp,
             $student->school,
             $student->address,
             $student->courses()->Name,
             $student->created_at->toDatestring(),
         ];
    }

    public function query()
    { 
        return Student::with('courses:id,Name')->whereIn('id',$this->selected);
    }
}
Nakov's avatar
Nakov
Best Answer
Level 73

@DInu98 So do you have Name property in your courses table, or is it name ?

You cannot do this btw: $student->courses()->Name, I showed you what to use above instead of that.

$student->courses->pluck('Name')->implode(', '),

because courses is a collection of MANY courses, not just one.

1 like
DInu98's avatar

@nakov yes I have Name property in courses. its working now.... but I didn't get enroll courses. in excel sheet address column data move to the enroll courses column. exported excel sheet like this

student id -> KTL-00000
student name -> chathura siva
contact ->3456789012
contact(whatsapp)->3456789012
school->st.thomas college
address->
enroll courses-> no 20/road/kandy
registeresd date->2021-10-19
Nakov's avatar

@DInu98 omg man, you need to check why is that, I can't help you one by one while you have the code and I am just guessing. But now this is really obvious, you should learn the basics on how it works. Look at your headings and then your map data.. I see that you have $student->email, in the map array, but you don't have a heading for the email. So that moves the address to show as a Course.

Then is your relationship working at all?

User::first()->courses will it return the courses of the first user in your database? You have to debug, trial and failure is the way we learn. I gave you an answer to your initial question, I cannot fix your own code for you.

It might also be because you use Name and it should be name I don't know.

$student->courses->pluck('name')->implode(', '),
1 like

Please or to participate in this conversation.