depsimon's avatar

Passing form data + file to an API

Hello everyone,

I've a L5 application that renders a form where the user can fill inputs and upload an image. This form is then sent to a Lumen API I built to persist the data.

I can easily send the classic inputs by catching them with Request::all(), but how can I pass the file as well ?

Here is my current code on the Laravel app, I'm using Guzzle to send my requests.

// EventController.php
public function store()
{
    // Some validation

    // Transform the data to give what the API expects
    $data = [
        'title'      => $this->request->input('title', ''),
        'content'    => $this->request->input('content', ''),
        'start_date' => $this->request->input('start_date'),
        'end_date'   => $this->request->input('end_date')
    ];
    $response = $this->client()->post('event', ['body' => $data]);
     // Handle the result
}
0 likes
2 replies
phildawson's avatar

You need to use the multipart, grabbing the contents from $request->file('file');

$this->client()->post('event', [
    'form_params' => $data,
    'multipart' => [
        [
            'name'     => 'file',
            'contents' => 'Hello World',
            'filename' => 'foo.txt'
        ]
    ]
]);
sibenye's avatar

@phildawson Yes you will need to use multipart but only multipart, you cannot combine both multipart and form_params according to guzzle docs

2 likes

Please or to participate in this conversation.