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

Laravel 8创建返回嵌套数组的POST接口及数据存储问题

Laravel API 创建数据返回200但未成功的解决方法及搜索关键词

我是Laravel新手,想要创建返回指定嵌套数组格式的API。已创建question_surveys数据表(含json类型的question字段),并编写了控制器存储代码,但在Postman中发起请求返回200状态码却未成功创建数据,希望得到解决方法及合适的搜索关键词。

期望响应格式

{
  "elements": [
    {
      "title": "Please indicate if you agree or disagree with the following statements",
      "question": [
        {
          "value": "affordable",
          "text": "Product is affordable"
        },
        {
          "value": "does what it claims",
          "text": "Product does what it claims"
        },
        {
          "value": "better then others",
          "text": "Product is better than other products on the market"
        },
        {
          "value": "easy to use",
          "text": "Product is easy to use"
        }
      ]
    }
  ]
}

迁移代码

Schema::create('question_surveys', function (Blueprint $table) {
    $table->id('question_survey_id');
    $table->string('title');
    $table->json('question');
    $table->timestamps();
});

原控制器代码

$validation = $request->validation([
    'title' => 'required|string',
    'question' => 'required|json',
]);

try {
    $response = QuestionSurvey::create($validation);
    return response()->json([
        'success' => true,
        'message' => 'Survey Question Successfully Created',
        'data' => $response,
        'code' => 200
    ], 200);
} catch (\Exception $e) {
    return response()->json([
        'message' => 'Something wrong, content was not created successfully',
        'errors' => $e->getMessage()
    ]);
}

解决方法

  • 修复验证方法调用错误:Laravel中请求验证的正确方法是$request->validate(),而非$request->validation()(后者不存在),错误的方法会导致验证逻辑失效,后续代码无合法数据却返回成功状态。修改后:
    $validation = $request->validate([
        'title' => 'required|string',
        'question' => 'required|array',
        'question.*.value' => 'required|string',
        'question.*.text' => 'required|string'
    ]);
    
  • 修正question字段验证规则:前端传入的是嵌套数组(不是JSON字符串),因此将json规则改为array,同时添加嵌套字段验证,确保每个question元素的value和text合法。
  • 设置模型批量赋值白名单:在QuestionSurvey模型中添加$fillable属性,允许title和question字段被批量赋值:
    protected $fillable = ['title', 'question'];
    
    未设置$fillable或$guarded时,Laravel会阻止批量赋值,导致数据无法写入数据库。
  • 调整响应格式匹配需求:如果需要返回期望的elements嵌套结构,修改返回的JSON:
    return response()->json([
        'success' => true,
        'message' => 'Survey Question Successfully Created',
        'data' => [
            'elements' => [
                [
                    'title' => $response->title,
                    'question' => $response->question
                ]
            ]
        ],
        'code' => 200
    ], 200);
    

实用搜索关键词

  • Laravel API 返回200但未创建数据
  • Laravel validate 与 validation 区别
  • Laravel JSON字段批量赋值
  • Laravel 嵌套数组验证规则
  • Laravel 模型fillable设置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 18:58:33