PHP Development | Tutorial 11 | Laravel Collections Explained

by | Oct 6, 2025 | PHP Development, Web App Development | 0 comments

Working with arrays in raw PHP can be clunky—especially when you need to filter, transform, or manipulate large datasets. Laravel solves this with Collections, a powerful wrapper around PHP arrays that provides a clean, chainable API for data manipulation.

Collections are used everywhere in Laravel—when fetching records from Eloquent, working with APIs, or transforming data before sending it to the frontend. For interviews, questions about Collections methods, use cases, and performance are very common.

What are Collections in Laravel?

A Collection is an enhanced array object that provides helpful methods for data processing.

Example:

use Illuminate\Support\Collection;

$collection = collect([1, 2, 3, 4, 5]);

$filtered = $collection->filter(function ($value) {
    return $value > 2;
});

dd($filtered->all()); // [3, 4, 5]

👉 Unlike plain arrays, Collections come with dozens of helper methods like map, filter, pluck, groupBy, and reduce.

Why Use Collections?

  1. Readable, chainable methods → No need for nested loops.
  2. Consistency → Same methods across Eloquent, arrays, and APIs.
  3. Powerful transformations → Simplifies complex logic.
  4. Lazy evaluation with LazyCollection → Handles large datasets efficiently.

Common Collection Methods with Examples

1. map() → Transform items

$users = collect(['Karthick', 'Jegan', 'Muthu']);
$upper = $users->map(fn($name) => strtoupper($name));

dd($upper->all()); // ['KARTHICK', 'JEGAN', 'MUTHU']

2. filter() → Keep matching items

$numbers = collect([10, 20, 30, 40]);
$filtered = $numbers->filter(fn($n) => $n > 20);

dd($filtered->all()); // [30, 40]

3. pluck() → Extract a specific key

$users = collect([
    ['id' => 1, 'name' => 'Karthick'],
    ['id' => 2, 'name' => 'Jegan'],
]);

dd($users->pluck('name')->all()); // ['Karthick', 'Jegan']

4. reduce() → Aggregate values

$numbers = collect([1, 2, 3, 4]);
$sum = $numbers->reduce(fn($carry, $n) => $carry + $n, 0);

dd($sum); // 10

5. groupBy() → Group items

$orders = collect([
    ['id' => 1, 'status' => 'pending'],
    ['id' => 2, 'status' => 'completed'],
    ['id' => 3, 'status' => 'pending'],
]);

dd($orders->groupBy('status')->toArray());
/*
[
  "pending" => [
    ["id" => 1, "status" => "pending"],
    ["id" => 3, "status" => "pending"]
  ],
  "completed" => [
    ["id" => 2, "status" => "completed"]
  ]
]
*/

6. sortBy() & sortDesc() → Sort collections

$users = collect([
    ['name' => 'Jegan', 'age' => 28],
    ['name' => 'Karthick', 'age' => 32],
]);

$sorted = $users->sortBy('age');
dd($sorted->pluck('name')->all()); // ['Jegan', 'Karthick']

7. first() & last() → Get items quickly

$numbers = collect([5, 10, 15]);
dd($numbers->first()); // 5
dd($numbers->last());  // 15

Collections in Eloquent

When you fetch multiple records using Eloquent, you get a Collection instance, not just an array.

$users = User::where('active', 1)->get();

// $users is a Collection
$names = $users->pluck('name');

dd($names->all());

👉 This is why Collections are everywhere in Laravel—once you understand them, you unlock huge productivity.

Lazy Collections

For large datasets, Laravel provides LazyCollection, which processes items one by one instead of loading everything into memory.

User::cursor()->each(function ($user) {
    echo $user->name;
});

👉 Useful for handling millions of rows without memory issues.

Common Beginner Mistakes

  • Using loops when Collection methods exist (e.g., foreach instead of map).
  • Forgetting that get() returns a Collection, not a plain array.
  • Using all() unnecessarily → lose chainability.
  • Not using LazyCollection for huge datasets.

Example of fixing N+1 issue:

// Bad: multiple queries
$posts = Post::all();
foreach ($posts as $post) {
    echo $post->user->name;
}

// Good: eager loading
$posts = Post::with('user')->get();

Sample Interview Questions & Answers

Q: What is a Collection in Laravel?

A: A Collection is a wrapper around PHP arrays with helper methods for filtering, mapping, sorting, and aggregating data.

Q: Difference between map() and each() in Collections?

A: map() transforms and returns a new collection, while each() just iterates without modifying.

Q: How do you extract a specific column from a Collection?

A: Using pluck(). Example: $users->pluck('email').

Q: What is the difference between Collection and LazyCollection?

A: Collection loads all data into memory, LazyCollection loads items as needed—better for large datasets.

Q: How does Laravel use Collections with Eloquent?

A: When retrieving multiple rows with get(), Eloquent returns a Collection of models with full Collection methods.

Q: How can you solve performance issues when looping through large datasets?

A: Use LazyCollection via cursor(), process data in chunks, or use pagination.

Mini Project Idea

👉 Build a Student Score Report feature:

  • Store student marks in DB.
  • Fetch all results with Eloquent.
  • Use Collection methods (groupBy, avg, max) to calculate average scores per class.
  • Display results neatly with Blade.

Closing Note

Laravel Collections are one of the most powerful yet underrated features. They simplify data manipulation, make code more expressive, and integrate seamlessly with Eloquent.

Laravel Framework Mastery

Why Choose Laravel?
→ Discover why Laravel dominates modern PHP development

Laravel Routing & Middleware
→ Control application flow with routes and middleware layers

Laravel MVC Architecture
→ Build scalable apps using Models, Views, and Controllers

Laravel Artisan & Productivity Tools
→ Supercharge your workflow with Artisan commands and dev tools

Advantages of Eloquent ORM
→ Master database operations with Laravel’s powerful ORM

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *