You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FormData参数能否包含对象?Laravel接收时出现[object Object]异常

How to Handle Object Parameters in FormData with Laravel

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 and json_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 19:32:33