laravel

Laravel HTTP Client dynamic call HTTP Method


I want to make all requests dynamic rather than defining Http in each function followed by httpMethod like this.

Http::post()
Http::put()
Http::delete()

what i tried.

function send($method, $url) {
   Http::withToken($token)->{$method}($url)
}

function x() {
   return $this->send('GET', 'url')
}

My code above works fine and i dont know if call a function from variable output like {$method} is best practice. but I want something similar like Guzzle.

(new Client)->request($method, $url, $options)

Solution

  • if you take a look at the source code here https://github.com/illuminate/http/blob/a28981924d318272053b87712740868d9b44899e/Client/PendingRequest.php laravel is using Guzzle. so basicly Http Client is Guzzle.

    and every function like POST PUT etc call a function name send

    so you can just direct call send function like this.

    Http::withToken($token)
        ->send('POST', 'url', [
            'headers' => [...]
            'form_params' => [
                ...
            ]
        ])