When you want to map paginated data and return only a subset of the fields, use through
rather than map
. The map
breaks the pagination object and changes it's identity. While, through
works on the paginated data itself
1// Don't: Mapping paginated data 2$employees = Employee::paginate(10)->map(fn ($employee) => [ 3 'id' => $employee->id, 4 'name' => $employee->name 5]) 6 7// Do: Mapping paginated data 8$employees = Employee::paginate(10)->through(fn ($employee) => [ 9 'id' => $employee->id,10 'name' => $employee->name11])
Tip given by @bhaidar