126 words, 1 min read

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):

<?php
<?php
$users = User::paginate(10)->map(fn ($user) => [
'id' => $user->id,
'name' => $user->name;
]);

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

<?php
<?php
$users = User::paginate(10)->through(fn ($user) => [
'id' => $user->id,
'name' => $user->name;
]);

Thanks to @bhaidar for the tip.