Skip to content

Conversation

@jessarcher
Copy link
Member

@jessarcher jessarcher commented Oct 22, 2025

When using the Http::batch method (#56946), the results are currently sorted in the order that the responses came back, rather than the order that the requests were defined:

dump(Http::batch(fn (Batch $batch) => [
    $batch->get('https://httpbin.org/delay/3'),
    $batch->get('https://httpbin.org/delay/2'),
    $batch->get('https://httpbin.org/delay/1'),
])->send());

array:3 [
  2 => Illuminate\Http\Client\Response {#419}
  1 => Illuminate\Http\Client\Response {#374}
  0 => Illuminate\Http\Client\Response {#328}
]

While the keys are maintained, the results array is no longer a list, and the iterating order is likely unexpected.

This differs from the Http::pool method, which always returns the results in the same order:

dump(Http::pool(fn (Pool $pool) => [
    $pool->get('https://httpbin.org/delay/3'),
    $pool->get('https://httpbin.org/delay/2'),
    $pool->get('https://httpbin.org/delay/1'),
]));

array:3 [
  0 => Illuminate\Http\Client\Response {#327}
  1 => Illuminate\Http\Client\Response {#373}
  2 => Illuminate\Http\Client\Response {#418}
]

This PR fixes this by sorting the results before they are returned, respecting any requests named with the as method.

I wasn't able to write a good test for this without hitting an external URL, because faked requests don't run async and always return in the correct order. I added a comment in lieu of a test.

I can confirm the following test passes (but would slow down the test suite and could be flaky):

public function testBatchResultsAreReturnedInTheSameOrderAsRequested(): void
{
    $responses = $this->factory->batch(function (Batch $batch) {
        return [
            $batch->get('https://httpbin.org/delay/3'),
            $batch->get('https://httpbin.org/delay/2'),
            $batch->get('https://httpbin.org/delay/1'),
        ];
    })->send();

    $this->assertSame([0, 1, 2], array_keys($responses));
    $this->assertTrue(array_is_list($responses));

    $responses = $this->factory->batch(function (Batch $batch) {
        return [
            $batch->as('c')->get('https://httpbin.org/delay/3'),
            $batch->as('b')->get('https://httpbin.org/delay/2'),
            $batch->as('a')->get('https://httpbin.org/delay/1'),
        ];
    })->send();

    $this->assertSame(['c', 'b', 'a'], array_keys($responses));
}

@taylorotwell taylorotwell merged commit 4598583 into 12.x Oct 22, 2025
65 of 67 checks passed
@taylorotwell taylorotwell deleted the http-batch-result-ordering branch October 22, 2025 19:32
@utsavsomaiya
Copy link
Contributor

Love it ❤️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants