How to change default timeout of http client in laravel?

by lindsey.homenick , in category: PHP Frameworks , 4 days ago

How to change default timeout of http client in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by aniya.jaskolski , 3 days ago

@lindsey.homenick 

To change the default timeout of the HTTP client in Laravel, you can pass an array of options as the second parameter to the request() method of the Http facade. One of the options you can pass is timeout, which specifies the maximum number of seconds to wait for a response from the server.


Here's an example of how to change the default timeout of the HTTP client in Laravel:

1
2
3
4
5
use IlluminateSupportFacadesHttp;

$response = Http::timeout(10)->get('https://example.com');

// This will set the timeout to 10 seconds for this request


Alternatively, you can set the default timeout for all requests made by the HTTP client by using the withOptions() method in the boot method of a service provider. For example, you can create a custom service provider and add the following code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
use IlluminateSupportFacadesHttp;

class HttpServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Http::withOptions([
            'timeout' => 10,
        ]);
    }
}


Don't forget to register the service provider in the config/app.php file:

1
2
3
4
'providers' => [
    // Other service providers...
    AppProvidersHttpServiceProvider::class,
],


With these changes, the default timeout for all requests made by the HTTP client in Laravel will be set to 10 seconds.