FormData参数能否包含对象?Laravel接收时出现[object Object]异常
Hey there! Let's tackle your question step by step:
Can FormData include objects?
Short answer: No, not directly. When you append a non-string/Blob/File value to FormData, the browser automatically converts it to a string using toString(), which is exactly why your server ends up with "[object Object]" for the favorite field.
Fixing the issue in your Laravel app
You’ve got two solid options to handle this correctly, depending on your use case:
Option 1: Serialize the object to JSON (great for complex structures)
First, adjust your frontend code to turn the object into a JSON string before adding it to FormData:
formData.append('first_name', 'takuya'); formData.append('last_name', 'yamamoto'); // Convert the object to a JSON string before appending formData.append('favorite', JSON.stringify({color: 'red', sports: "tennis"}));
Then in your Laravel controller, use $request->input() (not $request->file()!) to fetch the string, and decode it back to an array or object:
// Retrieve the JSON string and decode it to an associative array $favorite = json_decode($request->input('favorite'), true); // Now you can access values like this: $userFavoriteColor = $favorite['color']; // Returns 'red' $userFavoriteSport = $favorite['sports']; // Returns 'tennis'
Important note: $request->file() is exclusively for handling uploaded files (like images or documents). Your favorite field is a plain text JSON string, so input() is the correct method here.
Option 2: Break the object into nested FormData fields (ideal for simple structures)
If you prefer to keep the data as separate form fields, append each property of the object using nested syntax:
formData.append('first_name', 'takuya'); formData.append('last_name', 'yamamoto'); // Append each object property with nested field names formData.append('favorite[color]', 'red'); formData.append('favorite[sports]', 'tennis');
In Laravel, you can directly retrieve the entire favorite array with $request->input():
$favorite = $request->input('favorite'); // This gives you a ready-to-use array: ['color' => 'red', 'sports' => 'tennis']
Quick Recap
- FormData doesn’t support raw objects—they get converted to
"[object Object]"automatically. - Use
JSON.stringify()on the frontend andjson_decode()in Laravel for complex object structures. - For simpler objects, split them into nested FormData fields to get a pre-built array in Laravel.
- Avoid
$request->file()for non-file fields—stick to$request->input()or$request->get()for regular form data.
内容的提问来源于stack exchange,提问作者figalo66

