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

DarkaOnLine/l5-swagger Laravel数组参数被转为字符串如何解决

问题原因

你当前使用multipart/form-data类型提交请求(因为包含文件上传参数),swagger-ui默认会将注解定义的数组参数序列化为逗号拼接的字符串,而非标准的数组传递格式。

修复方法

只需要在businesses参数的@OA\Property注解中新增collectionFormat配置,同时根据Laravel的参数接收规则调整参数名即可,修改后的注解代码如下:

/**
 * @OA\Post(
 * path="/api/update-landing-page",
 * summary="Update Landing Page",
 * description="Update Landing Page",
 * tags={"Landing Page Backend"},
 * security={{"bearer": {} }},
 *   @OA\RequestBody(
 *       required=true,
 *       @OA\MediaType(
 *           mediaType="multipart/form-data",
 *           @OA\Schema(
 *               required={"businesses","image"},
 *               @OA\Property(
 *                   property="businesses[]",
 *                   description="Business ID",
 *                   type="array",
 *                   collectionFormat="multi",
 *                   @OA\Items(type="string", format="id"),
 *               ),
 *               @OA\Property(property="image", type="string", format="binary")
 *           )
 *       )
 *   ),
 * @OA\Response(
 *    response=200,
 *    description="",
 *          @OA\MediaType(
 *              mediaType="application/json",
 *          )
 *     )
 * )
 */

改动点说明:

  • 把property="businesses"改为property="businesses[]",符合form-data格式传递数组的命名规范,Laravel接收到后会自动解析为数组
  • 新增collectionFormat="multi"配置,告诉swagger-ui将数组拆分为多个同名参数传递,而非拼接为逗号字符串

验证操作

修改完成后执行命令重新生成swagger文档:

php artisan l5-swagger:generate

刷新swagger页面重新发起请求,即可在浏览器调试工具中看到businesses[]参数会按照businesses[]=1&businesses[]=2&businesses[]=3的格式传递,在Laravel代码中直接通过$request->input('businesses')就能拿到数组格式的参数。

可选兼容方案

如果不想修改参数名,也可以在后端接收时手动处理字符串转数组:

$businesses = explode(',', $request->input('businesses'));

内容的提问来源于stack exchange,提问作者Lee Soon Fatt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 14:24:02