Collections

Contents
Collect anything
Map and filter
Group by
Lazy note

Collect anything

The collect helper wraps any array in a fluent object with dozens of chainable methods. Once wrapped, sorting, filtering, and reshaping need no manual loops at all.

$names = collect(["ada", "bob", "cid"]); echo $names->count(); echo $names->first();

Map and filter

The map method rebuilds every item through a callback, while filter keeps only items that pass a check. Chain values at the end to renumber keys after removals.

$result = collect([1, 2, 3, 4]) ->map(function ($n) { return $n * 2; }) ->filter(function ($n) { return $n > 4; }) ->values(); print_r($result->all());

Group by

The groupBy method clusters rows that share a field value, such as users with the same role. Each cluster keeps its original rows, ready for counting or listing.

$rows = [ ["role" => "admin", "name" => "Ada"], ["role" => "editor", "name" => "Bob"], ]; $byRole = collect($rows)->groupBy("role"); echo $byRole->count();

Lazy note

Huge datasets do not fit in memory at once, so collections can stream items one by one. The lazy method returns a lazy collection that only pulls each value when the chain actually needs it.

$big = collect(range(1, 100000))->lazy(); $first = $big->take(5); print_r($first->all());

Next: Carbon dates

Article author: Arthur Isaev

Related articles
Development with PHP
What is Laravel and where it runs
Install Laravel
Your first route
Controllers
Blade basics
Blade advanced
Migrations
Eloquent models
Relationships
Query builder
Seeders and factories
Validation
Auth intro
Hand-rolled login
Middleware
Service container
Config and env
Artisan commands
Events and listeners
Queues
Mail
Cache
Sessions in Laravel
CSRF
Hashing
Sanctum tokens
API resources
Gates and policies
Notifications
Scheduler
Filesystem
Localization
Testing
HTTP tests
Collections
Carbon dates
Pagination
File uploads
Eloquent advanced
Transactions and locks
Deployment
Debugbar and dd
Broadcasting
Full-text search
Capstone: blog
Capstone: JSON API
Capstone: shop cart
Performance: kill N+1
Modern Laravel tour
Hero roadmap: the whole course on one page
Banner image

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: