Laravel - Collections - Method Sliding

The sliding method returns a new collection of chunks representing a "sliding window" view of the items in the collection:

    
    $collection = collect([1, 2, 3, 4, 5]);
    
    $chunks = $collection->sliding(2);
    
    $chunks->toArray();
    
    // [[1, 2], [2, 3], [3, 4], [4, 5]]
	

This is especially useful in conjunction with the eachSpread method:

    
    $transactions->sliding(2)->eachSpread(function ($previous, $current) {
        $current->total = $previous->total + $current->amount;
    });
	

You may optionally pass a second "step" value, which determines the distance between the first item of every chunk:

    
    $collection = collect([1, 2, 3, 4, 5]);
    
    $chunks = $collection->sliding(3, step: 2);
    
    $chunks->toArray();
    
    // [[1, 2, 3], [3, 4, 5]]