skip to Main Content

I am facing a problem with "A ‘contents’ key is required". I have been searching through but does not get the right answers. Here is my code

     $response = Http::withHeaders([
        'Accept'=>'application/json',
    ]);
    foreach($vault->ad_images as $image){
        if(Storage::exists($image)){
            $path = Storage::path($image);
            $file = fopen($path,'r');
            $response = $response->attach('images[]',$file);
        }
    }

    $response = $response->post($apiUrl,[$data]);
    $response = json_decode($response->body(),true);

I have searching through about the problem, it said the the contents is required where the files is actually exists in the storage. I even trace the fopen and get this result

stream resource @25 ▼ // app/Http/Controllers/Agc/PropertyVaultController.php:564
  timed_out: false
  blocked: true
  eof: false
  wrapper_type: "plainfile"
  stream_type: "STDIO"
  mode: "r"
  unread_bytes: 0
  seekable: true
  uri: "/home/ita/public_html/v2/storage/app/public/uploads/images/2023/11/291/395048-1700795192.jpg"
  options: []
}

This is really confusing since its just actually happen. Last time it works without any problem with this code.

2

Answers


  1. attach method accepts name and contents (string value), you pass resourse.

    $file = fopen($path,'r');
    $contents = stream_get_contents($file);
    
    $response->attach('fileName', $contents);
    
    Login or Signup to reply.
  2. From laravel docs and from api doc, this method you have 4 parameters. They are these:

    string|array $name-> name of the file

    string|resource $contents -> its contents. //ex: file_get_contents('photo.jpg') or fopen('photo.jpg', 'r');

    string|null $filename -> file’s filename

    array $headers -> // ex: ['Accept'=>'application/json']

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search