Search code examples
laravelfile-uploadguzzle

Laravel HTTP client attach multiple files


I am trying to make POST to a rest API where I need to send multiple files from a user input form. I have managed to get it to work with a single file, but when there are multiple files sent as an array ($file[]), I can't see anything in the laravel docs to show how this can be done.

$response = 'API_URL';
        $response = Http::withToken(ENV('API_KEY'))
        ->attach('file', fopen($request->file, 'r'))
        ->post($url, [
           'uuid' => $request->uuid,
        ]);

Solution

  • You can do it by:

    ->attach('file[0]', fopen($request->file[0], 'r'))
    ->attach('file[1]', fopen($request->file[1], 'r'))
    

    if your $files is an array of files that wants to send, you can do like below:

    $response = Http::withToken(ENV('API_KEY'));
    
    foreach ($files as $k => $file) {
      $response = $response->attach('file['.$k.']', $file);
    }
    
    $response = $response->post($url, [
      'uuid' => $request->uuid,
    ]);