And will it work if you add comma separated list of courses the user has been enrolled in?
$student->courses->pluck('Name')->implode(', '),
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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');
}
@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.
Please or to participate in this conversation.