Mahmoud Al-HabashOpen to new projects
  • WorkWork
  • ServicesServices
  • LabLab
  • WritingWriting
  • ContactContact
Amman--:--عربي
Writing/Laravel

Laravel Collections: Hidden Gems You Should Know

Discover powerful Laravel collection methods that will make your code cleaner and more efficient.

24 December 20251 min readLaravelاقرأ بالعربية

On this page

  1. Partition - Split Based on Condition
  2. Pipe - Transform the Collection
  3. When - Conditional Manipulation

Laravel collections have many powerful methods:

Partition - Split Based on Condition

php
[$admins, $users] = User::all()->partition(fn($user) => $user->isAdmin());

Pipe - Transform the Collection

php
$result = collect([1, 2, 3])->pipe(function ($collection) {
    return $collection->sum();
});

When - Conditional Manipulation

php
$collection = collect([1, 2, 3])
    ->when(true, fn($c) => $c->push(4));

These methods help you write more expressive and maintainable code.

All articles

Keep reading

  • Laravel Action Classes Pattern16 January 20261 min read
  • Laravel Action Classes: Single Responsibility16 January 20261 min read
  • Laravel API Rate Limiting16 January 20261 min read