Laravel API check if client http connection is still alive

  http, laravel, rest

In Laravel we have an api endpoint that may take a few minutes. It’s processing an input in batches and giving a response when all batches are processed. Pseudo-code below.

Sometimes it takes too long for the user, so the user navigates away and the connection is killed client-side. However, the backend processing still continues until the backend tries to return the response with a broken pipe error.

To save ressources, we’re looking for a way to check after each batch if the client is still connected with a function like check_if_client_is_still_connected() below. If not, an error is raised and processing is stopped. Is there a way to achieve this ?

function myAPIEndpoint($all_batches){
    $result = [];
    for ($batch in $all_batches) {
       $batch_result = do_something_long($batch);
       $result = $result + $batch_result;
    return result;

PS: I know async tasks or web sockets could be more appropriate for long requests, but we have good reasons to use a standard http endpoint for this.

Source: Laravel

Leave a Reply