Skip to content

Collections

Learn how to work with collections of DTOs using DataCollection.

Collections allow you to work with multiple DTO instances as a group:

$users = UserDTO::collection($userArray);
// DataCollection of UserDTO instances
$users->filter(fn($user) => $user->age > 18);
$users->map(fn($user) => $user->name);
$users->first();
$users->count();
$data = [
['name' => 'John', 'email' => 'john@example.com'],
['name' => 'Jane', 'email' => 'jane@example.com'],
];
$users = UserDTO::collection($data);
$users = User::all();
$dtos = UserDTO::collection($users);
use Event4u\DataHelpers\SimpleDTO\DataCollection;
$collection = DataCollection::make($data, UserDTO::class);
$adults = $users->filter(fn($user) => $user->age >= 18);
$names = $users->map(fn($user) => $user->name);
$first = $users->first();
$last = $users->last();
$count = $users->count();
$array = $users->toArray();
$paginated = UserDTO::paginatedCollection($users, page: 1, perPage: 10);
// [
// 'data' => [...],
// 'meta' => [
// 'current_page' => 1,
// 'per_page' => 10,
// 'total' => 100,
// 'last_page' => 10,
// ],
// ]
$users = User::paginate(10);
$dtos = UserDTO::collection($users);
class OrderDTO extends SimpleDTO
{
public function __construct(
public readonly int $orderId,
public readonly DataCollection $items, // Collection of OrderItemDTO
) {}
}
$order = OrderDTO::fromArray([
'orderId' => 123,
'items' => [
['product' => 'Widget', 'quantity' => 2],
['product' => 'Gadget', 'quantity' => 1],
],
]);
// ✅ Good - with type hint
public readonly DataCollection $items;
// ❌ Bad - no type hint
public readonly $items;
// ✅ Good - use collection methods
$adults = $users->filter(fn($user) => $user->age >= 18);
// ❌ Bad - manual loop
$adults = [];
foreach ($users as $user) {
if ($user->age >= 18) {
$adults[] = $user;
}
}

The following working examples demonstrate this feature:

All examples are fully tested and can be run directly.

The functionality is thoroughly tested. Key test files:

Run the tests:

Terminal window
# Run tests
task test:unit -- --filter=Collection