Overview
ListCollection provides static factory methods as convenient alternatives to the constructor. All factory methods returnListCollection instances with sequential integer keys.
make()
Create a new ListCollection instance from an array or iterable.Signature
The items to include in the collection. Can be an array, Collection, or iterable.
ListCollection - New collection with sequential keys.
Examples
Create from array
Create from associative array
Create empty collection
Usage Pattern
Themake() method provides a more fluent alternative to the constructor:
times()
Create a collection by invoking a callback a given number of times.Signature
The number of times to invoke the callback.
Callback that receives the iteration number (1-indexed). If omitted, returns the iteration numbers.
ListCollection - New collection with generated values.
Examples
Generate with callback
Generate sequence
Generate objects
Use Cases
- Generating test data: Create mock objects for testing
- Pagination: Generate page numbers
- Initialization: Create default structures
- Iteration: Repeat an operation n times
wrap()
Wrap a value in a ListCollection. If already a collection, returns as-is.Signature
The value to wrap. Can be a single value, array, or existing collection.
ListCollection - Collection containing the value(s).
Examples
Wrap single value
Wrap array
Wrap existing collection
Wrap null
Use Cases
- Defensive programming: Ensure you have a collection
- API flexibility: Accept single values or arrays
- Type normalization: Unified handling of various input types
Comparison with Constructor
Constructor
- Direct instantiation
- Requires
newkeyword - Explicit type declaration
make()
- Static factory method
- More fluent API
- Identical behavior to constructor
times()
- Generates values programmatically
- Callback receives iteration number
- Useful for creating sequences
wrap()
- Safely wraps any value
- Handles collections, arrays, and scalars
- Returns existing collections as-is
Practical Examples
Generate ID sequence
Create test users
Flexible input handling
Key Points
- All factory methods return
ListCollectionwith sequential keys (0, 1, 2, …) make()is a fluent alternative to the constructortimes()generates values programmatically using a callbackwrap()safely ensures you have a collection, regardless of input type- Factory methods are inherited from Laravel’s
Collectionbut returnListCollectioninstances - All methods respect the automatic reindexing behavior of
ListCollection