Collections & Helpers

Interview Questions: Data Manipulation, Higher Order Messages, and Pipelines

Q1: What is a Laravel Collection and how does it differ from a PHP array?

Concept: A Collection is a wrapper around native PHP arrays that provides a fluent, convenient interface for working with data. It comes with dozens of helper methods to chain operations.

Key Differences:

  • Object-Oriented: Collections are objects, arrays are primitives.
  • Chaining: You can chain methods like ->filter()->map()->sort().
  • Lazy Collections: Can handle massive datasets by loading one item at a time (using Generators) to save memory.

Q2: Explain the difference between `map()` and `transform()`.

Both iterate over the collection and modify items, but they behave differently regarding the original collection instance.

  • map(): Returns a new collection instance with the modified values. The original collection remains unchanged.
  • transform(): Modifies the collection in place. It returns the same collection instance but with mutated data.
$collection = collect([1, 2, 3]);

// Map returns new, original is [1, 2, 3]
$new = $collection->map(fn($x) => $x * 2); 

// Transform changes original to [2, 4, 6]
$collection->transform(fn($x) => $x * 2);

Q3: What are Higher Order Messages in Collections?

Higher Order Messages allow you to perform common actions on collections without writing a closure. They act as shortcuts for accessing properties or calling methods on objects within the collection.

// Without Higher Order Messages
$users->each(function($user) {
    $user->markAsActive();
});

// With Higher Order Messages
$users->each->markAsActive();

// Mapping a property
$emails = $users->map->email;

Q4: How would you handle a large CSV file import using Collections?

Using standard Collections would load the entire file into memory, likely causing a crash. The solution is Lazy Collections.

Lazy Collections use PHP Generators to read the file line-by-line, keeping memory usage low regardless of file size.

use Illuminate\Support\LazyCollection;

LazyCollection::make(function () {
    $handle = fopen('large-file.csv', 'r');
    while (($line = fgets($handle)) !== false) {
        yield str_getcsv($line);
    }
})->chunk(1000)->each(function ($chunk) {
    DB::table('records')->insert($chunk->toArray());
});

Q5: What is the `pipeline()` helper?

The Pipeline pattern allows you to pass an object through a series of "pipes" (classes or closures) to perform a sequence of operations. It is used internally by Laravel for middleware.

It is useful for complex filtering logic where you want to break down a large query builder into small, reusable classes.

$users = app(Pipeline::class)
    ->send(User::query())
    ->through([
        FilterActive::class,
        FilterSort::class,
        FilterSearch::class,
    ])
    ->thenReturn()
    ->get();