#database #development #laravel #php

Ever wanted to transform the paginator results to return a subset of fields and not all? Better use the through() function instead of the map() function.

Instead of doing this (which replaces the paginator with a new collection):

1$users = User::paginate(10)->map(fn ($user) => [
2    'id' => $user->id,
3    'name' => $user->name;
4]);

You should be using the through method instead (which keeps the result a paginator):

1$users = User::paginate(10)->through(fn ($user) => [
2    'id' => $user->id,
3    'name' => $user->name;
4]);

Thanks to @bhaidar for the tip.