Search code examples
laravellaravel-api

Laravel HTTP client - How to send file


I have one controller function like

public function storeBlog(Request $request)
{
  // Here i am receiving file like $request->file('image');
}

Now I want to send that file to an API endpoint like

Http::post('http://example.com/v1/blog/store', $request->all());

I am getting all the request but not file, I know we need to pass POST data as a multipart. How can I do that?


Solution

  • You should use Http::attach to upload a file.

    public function storeBlog(Request $request)
    {
        // check file is present and has no problem uploading it
        if ($request->hasFile('image') && $request->file('photo')->isValid()) {
            // get Illuminate\Http\UploadedFile instance
            $image = $request->file('image');
    
            // post request with attachment
            Http::attach('attachment', file_get_contents($image), 'image.jpg')
                ->post('example.com/v1/blog/store', $request->all());
        } else {
            Http::post('http://example.com/v1/blog/store', $request->all());
        }
    }