Guzzle is a PHPHTTP Client for sending HTTP requests to APIs. But sending multiple files with a single request sometimes bring on a lot of complexity and people get confused in sending arrays of data within an array for a multipart form, quite confusing.
This snippet will explain how to send multiple files or images with a single request through Guzzle HTTP client with ease. So let's dive straight in the code.
$output = [];
foreach ( $images['image'] as $key => $value ) {
if ( ! is_array( $value ) ) {
$output[] = [
'name' => 'image[]',
'contents' => fopen( $value->getPathname(), 'r' ),
'filename' => $value->getClientOriginalName()
];
continue;
}
}
$output [] =
[
'name' => 'field_name',
'contents' => \request()->get( 'field_name' )
];
$output [] = [
'name' => 'field_name_2',
'contents' => \request()->get( 'field_name_2' )
];
$output [] = [
'name' => 'field_name_3',
'contents' => \request()->get( 'field_name_3' )
];
$client = new Client( [ 'base_uri' => "http://api_url.dev/", ] );
$response = $client->request( 'POST', 'api/endpoint', [ 'headers' => [ 'Authorization' => $token ], 'multipart' => $output ] ); $data = \GuzzleHttp\json_decode( $response->getBody() );
Try it out and let us know in the comment section if you faced any issue. Cheers!
Do follow us on Twitter.

