Your First ListCollection
Let’s create a simple ListCollection and explore its core behavior.
Import the class
First, import the ListCollection class in your PHP file: use dhy\LaravelList\ ListCollection ;
Create a ListCollection
Create a new ListCollection with some data: $list = new ListCollection ([ 1 , 2 , 3 , 4 , 5 ]);
// Check the contents
$list -> all (); // [0 => 1, 1 => 2, 2 => 3, 3 => 4, 4 => 5]
Notice the keys are sequential: 0, 1, 2, 3, 4.
Perform operations
Now let’s filter the list to keep only values greater than 2: $filtered = $list -> filter ( fn ( $value ) => $value > 2 );
// Keys are automatically reindexed!
$filtered -> all (); // [0 => 3, 1 => 4, 2 => 5]
With standard Laravel Collections, this would return [2 => 3, 3 => 4, 4 => 5] with gaps in the keys. ListCollection automatically reindexes to maintain sequential keys.
The Reindexing Advantage
Let’s see automatic reindexing in action across different operations:
Constructor Reindexing
Removing Items
Sorting
Chaining Operations
// Associative array gets reindexed immediately
$list = new ListCollection ([ 'a' => 1 , 'b' => 2 , 'c' => 3 ]);
$list -> all (); // [0 => 1, 1 => 2, 2 => 3]
// Non-sequential keys also get reindexed
$list = new ListCollection ([ 5 => 'apple' , 10 => 'banana' , 15 => 'cherry' ]);
$list -> all (); // [0 => 'apple', 1 => 'banana', 2 => 'cherry']
Working with JSON
One of the most practical benefits of ListCollection is predictable JSON serialization:
use dhy\LaravelList\ ListCollection ;
// Create a filtered list
$numbers = new ListCollection ([ 1 , 2 , 3 , 4 , 5 , 6 ]);
$evenNumbers = $numbers -> filter ( fn ( $n ) => $n % 2 === 0 );
// Convert to JSON
echo $evenNumbers -> toJson ();
// Output: [2,4,6]
// ↑
// JSON array, not an object!
// Compare with standard Collection:
$standardCollection = collect ([ 1 , 2 , 3 , 4 , 5 , 6 ])
-> filter ( fn ( $n ) => $n % 2 === 0 );
echo $standardCollection -> toJson ();
// Output: {"1":2,"3":4,"5":6}
// ↑
// JSON object with string keys
Common Operations
Here are some common operations you’ll use with ListCollection:
Adding Items
$list = new ListCollection ([ 'a' , 'b' ]);
// Append to the end
$list -> push ( 'c' );
$list -> all (); // [0 => 'a', 1 => 'b', 2 => 'c']
// Add to the beginning
$list -> prepend ( 'z' );
$list -> all (); // [0 => 'z', 1 => 'a', 2 => 'b', 3 => 'c']
// Using array syntax
$list [] = 'd' ;
$list -> all (); // [0 => 'z', 1 => 'a', 2 => 'b', 3 => 'c', 4 => 'd']
Removing Items
$list = new ListCollection ([ 'apple' , 'banana' , 'cherry' , 'date' ]);
// Remove by index
$list -> forget ( 1 );
$list -> all (); // [0 => 'apple', 1 => 'cherry', 2 => 'date']
// Remove and return
$item = $list -> pull ( 0 );
echo $item ; // 'apple'
$list -> all (); // [0 => 'cherry', 1 => 'date']
// Remove from end
$last = $list -> pop ();
echo $last ; // 'date'
$list -> all (); // [0 => 'cherry']
$list = new ListCollection ([ 1 , 2 , 3 , 4 ]);
// Map to new values
$doubled = $list -> map ( fn ( $n ) => $n * 2 );
$doubled -> all (); // [0 => 2, 1 => 4, 2 => 6, 3 => 8]
// Transform in place
$list -> transform ( fn ( $n ) => $n * 10 );
$list -> all (); // [0 => 10, 1 => 20, 2 => 30, 3 => 40]
// Filter with callback
$list = new ListCollection ([ 1 , 2 , 3 , 4 , 5 , 6 ]);
$odds = $list -> filter ( fn ( $n ) => $n % 2 !== 0 );
$odds -> all (); // [0 => 1, 1 => 3, 2 => 5]
Practical Example: Processing API Data
Let’s build a realistic example of processing user data for an API response:
use dhy\LaravelList\ ListCollection ;
// Simulate fetching users from database
$users = [
[ 'id' => 5 , 'name' => 'Charlie' , 'active' => false , 'role' => 'user' ],
[ 'id' => 1 , 'name' => 'Alice' , 'active' => true , 'role' => 'admin' ],
[ 'id' => 3 , 'name' => 'Bob' , 'active' => true , 'role' => 'user' ],
[ 'id' => 8 , 'name' => 'Diana' , 'active' => true , 'role' => 'user' ],
[ 'id' => 2 , 'name' => 'Eve' , 'active' => false , 'role' => 'user' ],
];
// Process with ListCollection
$activeUserList = ( new ListCollection ( $users ))
// Keep only active users
-> filter ( fn ( $user ) => $user [ 'active' ])
// Sort by name
-> sortBy ( 'name' )
// Extract just the data we need
-> map ( fn ( $user ) => [
'id' => $user [ 'id' ],
'name' => $user [ 'name' ],
'role' => $user [ 'role' ],
]);
// Convert to JSON for API response
echo $activeUserList -> toJson ();
/* Output (formatted for readability):
[
{"id":1,"name":"Alice","role":"admin"},
{"id":3,"name":"Bob","role":"user"},
{"id":8,"name":"Diana","role":"user"}
]
Notice:
- Array keys are sequential [0, 1, 2]
- JSON is a true array, not an object
- Perfect for frontend consumption
*/
Key Differences from Standard Collection
Some Collection methods are blocked because they would produce associative keys:$list = new ListCollection ([ 1 , 2 , 3 ]);
// These throw BadMethodCallException:
$list -> flip (); // Would swap keys and values
$list -> groupBy ( 'category' ); // Would create associative groups
$list -> keyBy ( 'id' ); // Would use 'id' as keys
$list -> countBy (); // Would create value => count map
$list -> mapWithKeys ( ... ); // Would create custom keys
This is by design! It prevents accidentally breaking the sequential key guarantee.
If you need these operations, use Laravel’s standard Collection class instead. Laravel List is specifically for when you need list behavior.
Static Factory Methods
You can also create ListCollection instances using static factory methods:
// Create from array
$list = ListCollection :: make ([ 1 , 2 , 3 ]);
// Generate with callback
$list = ListCollection :: times ( 5 , fn ( $i ) => $i * 10 );
$list -> all (); // [0 => 10, 1 => 20, 2 => 30, 3 => 40, 4 => 50]
// Wrap a single value
$list = ListCollection :: wrap ( 'hello' );
$list -> all (); // [0 => 'hello']
Next Steps
Core Concepts Learn about the reindexing mechanism, method overrides, and design philosophy.
API Reference Explore all available methods and their behavior with detailed examples.