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

AO's avatar
Level 1

Export to excel

Hello

I'm using this package:LaraveExcel

https://github.com/Maatwebsite/Laravel-Excel

I'm trying to export excel with a relation.

so in my UserExport :


/**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        
     $group = Group::findOrFail($id);
    $students = $group->students()->where('group_id', '=', $group->id)->get();
  

    }

I'm trying to export students from the group.

the group and users have a relation.

so I want to get all users in the group.

and only certain columns like name and full name etc.

any idea on how I can accomplish this?

0 likes
6 replies
tykus's avatar
tykus
Best Answer
Level 104

That query doesn't need an explicit where - it is already scoped using the $group model instance. This can be simplifed:

$students = $group->students; // ()->where('group_id', '=', $group->id)->get();

Are students and users the same, it is not clear?

You can also eager-load the group's students (users) with the selected Student columns using :

$group = Group::with('students:id,name,fullname')->findOrFail($id);
AO's avatar
Level 1

@tykus I'm getting this error :

1052 Column 'id' in field list is ambiguous

using :


$group = Group::with('students:id,name,fullname')->findOrFail($id);

tykus's avatar

students is a relation, right? What SQL query is actually being run?

AO's avatar
Level 1

it is a relation between App\Group and App\User

tykus's avatar

Ok. Am curious about the ambiguous id...

What SQL query is actually being run?

AO's avatar
Level 1

@tykus


SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in field list is ambiguous (SQL: select `id`, `group_user`.`group_id` as `pivot_group_id`, `group_user`.`user_id` as `pivot_user_id` from `users` inner join `group_user` on `users`.`id` = `group_user`.`user_id` where `group_user`.`group_id` in (2))

Please or to participate in this conversation.