Sitemap
tarfin

Tarfin Technology Blog

Validating `multipart/form-data` with Laravel Validation Rules with proper JSON data types

--

Photo by Ben Griffiths / Unsplash

This article co-written by Yunus Emre Deligöz, Oğuzhan Karacabay and available in both English and Turkish, co-published on my blog.

When you want both upload files and send JSON payload from a Frontend Single Page Application to your Laravel Backend API, you send it with a multipart/form-data encoding.

A typical example of doing this regardless of Frontend Frameworks would be:

As a good Laravel developer, you want to validate this payload with a Laravel Request class before it comes to the Controller.

The Laravel Controller might look more or less like this:

and an example Laravel Request class would probably look something like this:

So far, everything went perfectly, but when you run this code, you will notice that the data you sent did not pass the validation. Dig deeper and you’ll see that the data coming into your Laravel API is very different from what we expected:

So you noticed that multipart/formdata, in addition to its ability to both, send binary files and JSON payload, converts all data types to strings,.

After this step, you can change your validation rules assuming that the incoming data will be all string types, you can do your parse gymnastics to fully validate string-type values.

Validation with proper JSON Data Types

If the FormData object can only send data of string types and we must use a FormData object to upload files, we will use it in this way. Of course, by first converting all the data to be sent to a JSON string.

After adding the file we want to upload to FormData (I.), we convert all the payload to a JSON string with the stringify() function. (II.)

Thus, we have a FormData object containing only the file and payload to send to the Backend API. (III.)

We used parseFloat() function because the stringify() function cannot parse float types to a JSON string with correct data type. (IV.)

We need to convert the JSON string coming to the Backend API side into a JSON Payload just before passing it through the validation rules. The prepareForValidation() method in Laravel’s Request classes is there for just that.

After converting the JSON String to JSON Payload using the json_decode() function in the prepareForValidation() method, we combine it with other Request data with merge()which is another method of Laravel Request classes.

Thus, our data was cast into appropriate data types and passed all the validation rules. So there is no need to change the validation rules or do any additional validation gymnastics.

--

--

No responses yet