Use flatMap() to map over a collection and collapse the nested array result into a flat collection in a single operation.
Mapping over a collection where callbacks return sub-arrays creates nested array structures. Combining map() and collapse() into flatMap() simplifies transformations.
use App\Models\User;
// Maps over users and flattens all roles into a single flat collection
$roles = $users->flatMap(fn ($user) => $user->roles);
- Combines map() transformation and collapse() flattening in a single call
- Flattens nested array structures returned by mapping callbacks
- Keeps collection pipeline code concise
Related Tips
View all tips →
Laravel
Eloquent
Clean Up Collections with Higher-Order Collection Messages
Use higher-order collection proxies like $users->each->archive() or $orders->sum->total to replace verbose closure callbacks.
READ
>
Laravel
Eloquent
Stop Using get() Before Collection Chains: Use lazy()
Calling get() loads all matching rows into memory before filtering. Use lazy() to process database records lazily.
READ
>