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

React提交multipart/form-data至Laravel时数组验证失败求助

解决React向Laravel发送multipart/form-data时数组验证失败的问题

问题原因

使用multipart/form-data格式发送请求时,PHP(Laravel底层)不会自动将JSON字符串解析为数组,同时文件对象无法通过JSON.stringify正确传递,导致Laravel的数组验证规则触发422错误。

解决方案

1. 处理categories普通数组

不要将数组转为JSON字符串,而是通过多次调用FormData的append方法,使用categories[]作为键名,Laravel会自动将其识别为数组:

// 替换原有的categories append代码
const categories = ['sneakers', 'shoes'];
categories.forEach(category => {
  formData.append('categories[]', category);
});

2. 处理images文件数组

文件对象不能用JSON.stringify处理,同样需要循环数组,用images[]作为键名逐个添加文件:

// 替换原有的images append代码
productImages.forEach(image => {
  formData.append('images[]', image);
});

修改后的完整React代码

const handleUploadPictures = (event) => {
    const files = event.target.files;
    if (!files.length) return toast.error("You need to upload minimum 1 image.");

    setProductImages(Array.from(files));
};

const createProduct = async () => {
    const formData = new FormData();
    formData.append("name", productName);
    formData.append("title", productTitle);
    formData.append("subtitle", productSubTitle);
    formData.append("description", productDescription);
    
    // 处理categories数组
    const categories = ['sneakers', 'shoes'];
    categories.forEach(category => {
        formData.append('categories[]', category);
    });
    
    // 处理images文件数组
    productImages.forEach(image => {
        formData.append('images[]', image);
    });

    await axios
        .post(`${API_URL}/api/create/product`, formData, {
            headers: {
                "Content-Type": "multipart/form-data",
            },
        })
        .then((response) => {
            console.log(response.data);
            return response.data;
        })
        .catch((error) => {
            console.log(error);
            return getResponseValidationErrors(error) ?? formatResponseError(error, "We could not add the product.");
        });
}

验证规则无需修改

你的Laravel验证规则保持原样即可,因为前端传递的格式已经符合Laravel对数组参数的预期:

public function rules(): array
{
    return [
        'name' => 'required|min:3|max:255',
        'title' => 'required|min:3|max:255',
        'subtitle' => 'required|min:3|max:255',
        'description' => 'nullable|min:10|max:1000',
        'categories' => 'required|array',
        'images' => 'required|array|min:1|max:10',
        'images.*' => 'image|mimes:jpeg,png,jpg,gif|max:2048',
    ];
}

内容的提问来源于stack exchange,提问作者Galbert

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 14:57:06