marcopierac's avatar

Handling incoming FormData

Hello,

in my frontend i have the following object that i need to send to my backend:

let obj = {
  a: 123,
  b: "test",
  c: [ null, File ]
};

where File is a File object.

I am transforming this object into a correctly structured FormData object, like this:

let form = new FormData;
form.append("a", JSON.stringify(obj.a));
form.append("b", JSON.stringify(obj.b));
form.append("c[]", JSON.stringify(obj.c[0]));
form.append("c[]", obj.c[1]); // this is the file

The reason why i'm stringifying everything is simple: FormData only accepts and sends blobs or strings, so the number 123 would become "123" anyways, but the string "test" would remain "test"; i'm converting to json so that i can decode and figure out the correct types, afterwards.

The problem comes in my backend.

If, and only if, the request was a multipart form data, i have to pass every $request->input throughjson_decode, to get the original value with the correct type.

Normally, with application/json requests, i can access the correct value right away via the input method.

How can i "hook" into $request->input to do this just once? or how can i edit all of the incoming request inputs, just once?

Thanks in advance

Ps: I already thought about using a custom extension of the Request class, without success: https://laracasts.com/discuss/channels/lumen/extend-or-decorate-request-in-lumen-7

0 likes
2 replies
marcopierac's avatar

Hello sir,

by using form request validation class you mean creating a custom Request class and use that one in my controllers, correct?

I did not specify it in the title, but i'm using Lumen; the make:request command and FormRequests are not available on Lumen.

Anyway i already tried creating an extension of Illuminate\Http\Request, but everything breaks. I have already created a dedicated thread here: https://laracasts.com/discuss/channels/lumen/extend-or-decorate-request-in-lumen-7

Thank you for your time

Please or to participate in this conversation.