How to change default timeout of Http Client in Laravel – Laravel

by
Ali Hasan
aiohttp composer-php laravel

Quick Fix: Create a custom HTTP client factory that extends the default factory and overrides the __call method. In the overridden method, set the default timeout to the desired value using the withOptions method.

The Problem:

In Laravel, the default timeout for Http Client requests is 30 seconds. However, a user wants to change this to 5 seconds without manually calling the timeout(5) function on each Http instance. Upon trying to set the default timeout in the AppServiceProvider, the user encounters an issue where Http instances are reused across multiple API calls, leading to unexpected behavior. The user seeks a solution that allows for a default timeout of 5 seconds without the need for manual new() calls or a workaround that avoids reusing Http instances.

The Solutions:

Solution 1: Customization of HTTP Client Factory

The provided solution involves customizing the HTTP client factory to override the default timeout behavior. By creating a new class that extends the Factory class and binding it to the application, you can modify the factory’s default options to set the timeout to 5 seconds.

This customized factory wraps the newPendingRequest method of the factory, allowing you to intercept and modify the newly created HTTP requests before they are sent. Inside the factory class, the withOptions method is applied to each new request, ensuring that the timeout is set to the desired value of 5 seconds.

By binding this custom factory to the application, whenever the Factory class is called, an instance of the custom factory is created. This allows for the modification of the default timeout behavior without the need to make additional calls to the timeout function explicitly.

Q&A

How to set the default timeout value for a Laravel HTTP client to 5 seconds?

Override the Factory class and modify the default options within the __call method.

How to prevent reusing the same HTTP client instance for multiple API calls?

Create a new custom Factory class that returns a new PendingRequest instance for each call.

Video Explanation:

The following video, titled "Laravel Advanced - HTTP Client (Pool, Retry, Timeout, Basic Auth ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

In this video, I have explained every aspect of the Laravel HTTP client that comes by default on Laravel. You can send HTTP requests using ...