Use through instead of map when using pagination

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->name
11])

Tip given by @bhaidar

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord