Vimo's avatar
Level 4

Handling FormData null string

Since FormData only can contain strings or blobs, I was wondering how I would prevent the Laravel backend to store the data as the string "null" when using axios in my Vue project.

In my case, I use FormData to send an image along with some other data. Some of the table columns are nullable strings. When I try to save an empty field it get saved as "null" instead of NULL.

Should this be done in the frontend or backend? And how would it be done? Currently, I am doing a check in my frontend.

if (value != null) formData.append(key, value);

Note: The following middleware did not work for me on the backend side: \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class

0 likes
6 replies
bobbybouwmann's avatar

Laravel should do this automatically for you. It seems that your frontend is not sending those values as actual null values to the backend. Can you maybe show how you send it to the backend?

Vimo's avatar
Level 4

You are correct. The frontend is unable to pass the actual null value when using FormData because FormData cannot handle null. So it passes a string called "null" instead. When using axios without FormData, I get the desired result and null actually gets sent.

Maybe a better question would be if Laravel can or should handle the "null" string or it if should be done in the frontend.

bobbybouwmann's avatar
Level 88

This is something your frontend should fix in my opinion! Your backend has an API that either receives a string or NULL. If it sends "null" it should handle it as a string, since it's a string ;)

You can create a middleware for this, but that means your users can't use the string "null" anymore as input value. That decision is up to you ;)

1 like
Vimo's avatar
Level 4

Great input. I agree with you and will keep handling it on the frontend side.

Thanks!

mholmes's avatar

I handled this by json stringify the inputs on the client side and json decoding them on the server side.

Vimo's avatar
Level 4

I went with the approach to only check for null on the front end. Have been working well so far!

Please or to participate in this conversation.