Mastering New Collection and Utility Features in Laravel
Overview
Modern development requires tools that reduce boilerplate and simplify complex logic.
Prerequisites
To follow this guide, you should have a solid grasp of
Key Libraries & Tools
- Str Helper: The string utility class used for Markdown rendering.
- Number Helper: A utility class for handling numeric range operations.
- Collections: The core Laravelwrapper for arrays, now updated with multiplication capabilities.
Code Walkthrough
1. Markdown Extension Support
Previously, the Str::markdown() method handled standard
use Illuminate\Support\Str;
// Basic markdown conversion
$html = Str::markdown('# Hello World');
// New: With extensions
$html = Str::markdown($content, extensions: [
new CustomExtension(),
]);
2. Segmenting Data with Number Pairs
The Number::pairs() method allows you to split a total value into specific segments. This is perfect for generating time slots or paginated ranges.
use Illuminate\Support\Number;
// Create pairs up to 100, incrementing by 10
$ranges = Number::pairs(100, 10);
// Output: [[1, 10], [11, 20], ...]
You can adjust the starting offset as a third argument. Changing it to 0 would result in pairs like [0, 10], [11, 20].
3. Collection Multiplication
Testing UIs often requires more data than your local database contains. The multiply() method duplicates items within a collection without affecting your database state.
$users = User::all(); // Contains 1 user
// Multiply for UI testing
$dummyData = $users->multiply(3);
// Result: A collection containing 3 instances of the user
Syntax Notes
Notice the offset parameter in Number::pairs(). By default, multiply() method is a higher-order function that preserves the original collection type.
Practical Examples
Imagine a booking system for a clinic. If a shift is 540 minutes long and each appointment takes 45 minutes, Number::pairs(540, 45) generates every possible time slot range instantly. This eliminates manually calculating loop boundaries for your view templates.
Tips & Gotchas
When using multiply(), remember that it creates shallow copies of objects. If you modify a property on one "multiplied" item, it will reflect across all copies because they reference the same object instance in memory. For testing unique data, use
