Using chunkWhile() to Group Collections in Laravel

Laravel devs, here's a gem for you: πŸ’Ž
The chunkWhile() method in Laravel Collections is a powerful tool for dynamically grouping elements based on a condition. This example demonstrates how to group log entries by date.

Collection Example

use Illuminate\Support\Collection;

$logs = collect([
    ['timestamp' => '2024-01-01 00:00:00', 'message' => 'Log 1'],
    ['timestamp' => '2024-01-01 01:00:00', 'message' => 'Log 2'],
    ['timestamp' => '2024-01-02 00:00:00', 'message' => 'Log 3'],
    ['timestamp' => '2024-01-02 02:00:00', 'message' => 'Log 4'],
]);

$chunks = $logs->chunkWhile(function ($value, $key, $chunk) {
    return substr($value['timestamp'], 0, 10) === substr($chunk->last()['timestamp'], 0, 10);
});

$chunks->all();

Example Output

When executed, the code will produce:

[
    [
        {"timestamp": "2024-01-01 00:00:00", "message": "Log 1"},
        {"timestamp": "2024-01-01 01:00:00", "message": "Log 2"}
    ],
    [
        {"timestamp": "2024-01-02 00:00:00", "message": "Log 3"},
        {"timestamp": "2024-01-02 02:00:00", "message": "Log 4"}
    ]
]

Conclusion

The chunkWhile() method is a powerful addition to the Laravel Collection methods, allowing you to dynamically group items based on conditions. This can greatly enhance the efficiency and readability of your code when dealing with complex data grouping scenarios.

Found this helpful?

If this guide was helpful to you, subscribe to my daily newsletter and give me a follow on X/Twitter. It helps a lot!

Subscribe to Harris Raftopoulos

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe