Skip to content

Extends the native Laravel Http Client, so that you can define default options

License

Notifications You must be signed in to change notification settings

smokills/laravel-http-client-default-options

Repository files navigation

Image of package

Latest Version on Packagist Build Status Total Downloads License

Set default available options to the Laravel Http Client.

Installation

Install the package via composer:

composer require smokills/laravel-http-client-default-options

Laravel

In a Laravel environment, the package will be autoregistered thanks to the Laravel Package Auto-Discovery

Lumen

If You would like use this package within a Lumen installation, you have to register the Service Provider in the app/bootstrap.php

$app->register(Smokills\Http\ServiceProvider::class);

Usage

You may define global options for the Http client in following way

// In a boot Service provider method (ex: the AppServiceProvider)

public function boot()
{
    ...

    Http::withDefaultOptions([
        'base_uri' => 'https://foo.com',
        'headers' => [
            'X-Bar-Header' => 'bar'
        ],
    ]);
}

From now on, all subsequent request will use the default options we have provided:

// Somewhere in the code

/**
 * Since we have defined the base_uri as default option, we can simply make a
 * request using only the uri.
 */
$response = Http::get('/baz');

We can still continue add other options or helpers if we need:

// Somewhere in the code

/**
 * The debug option and the basic auth will be used together the default options defined before.
 */
$response = Http::withOptions([
    'debug' => 'true'
])->withBasicAuth('username', 'password')->get('/baz');

If you need to remove several or even all of the the default options, in order to make other requests, you may use the withoutDefaultOptions method.

// Remove all of the default options...
$response = Http::withoutDefaultOptions()->get('https://bar.com');

// Remove some of the global options
$response = Http::withoutDefaultOptions([
    'option', 'another-option'
])->get('https://bar.com');

// You can pass options to remove as arguments as well
$response = Http::withoutDefaultOptions('option', 'another-option')->get('https://bar.com');

// If you would like to remove deeply nested options, you may use the the dot notation syntax
$response = Http::withoutDefaultOptions('header.X-Some-Header')->get('https://bar.com');

Testing

composer test

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Credits

License

The MIT License (MIT). Please see License File for more information.

Laravel Package Boilerplate

This package was generated using the Laravel Package Boilerplate.