【问题标题】:Laravel - How can I post array of objects?Laravel - 我如何发布对象数组?
【发布时间】:2020-05-18 12:13:30
【问题描述】:

我有一个动态表,可以在其中添加和删除行。在每一行中,都有一些输入,用户可以在其中向对象添加数据。

现在,我将每个索引号硬编码为名称 attr。像这样:

<input type="text" name="reports[0][title]">
<input type="text" name="reports[0][description]">
<input type="text" name="reports[1][title]">
<input type="text" name="reports[1][description]">

是否可以这样做:

<input type="text" name="reports[][title]">
<input type="text" name="reports[][description]">
<input type="text" name="reports[][title]">
<input type="text" name="reports[][description]">

并像在硬编码索引时一样接收请求?

我需要将多个对象发布到控制器中的 store 方法。当我收到请求时,我希望数据是这样的,而不需要对索引进行硬编码。

"reports": [
    {
        "title": "Title 1",
        "description": "Description 1"
    },
    {
        "title": "Title 2",
        "description": "Description 2"
    }
]

提前致谢。

【问题讨论】:

    标签: html arrays laravel forms laravel-blade


    【解决方案1】:

    选项 2 是不可能的,这将导致如下结果:

    {
     _token: "OFjlTsy3Jws9xW9H0cI9ARVGGNnQokLtRI6Tn478",
     reports: [
      {
         title: "title 1"
      },
      {
         description: "description 1"
      },
      {
         title: "title 2"
      },
      {
         description: "description 2"
      },
     ],
    }
    

    因此,在动态添加字段时,您需要将它们与每组的数字一起添加:

    假设这是你的表单

    <form action="save-reposts" method="POST">
      <!-- Your crsf token field here -->
      <input type="text" name="reports[0][title]">
      <input type="text" name="reports[0][description]">
      <input type="text" name="reports[1][title]">
      <input type="text" name="reports[1][description]">
      <input type="submit" id="submitButton" value="Submit" />
    </form>
    <button id="addMoreReports"> Add more </button>
    

    使用 jQuery 可能是这样的:

    let i = 2;
    $('#addMoreReports').click(function(){
       $('#submitButton').before(addFieldSet(i));
       i++;
    });
    
    function addFieldSet(index){
       return '<input type="text" name="reports[' + index + '][title]"><input type="text" name="reports[' + index + '][description]">';
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-09
      • 2019-10-17
      • 2011-12-05
      • 2019-12-06
      • 2021-11-23
      • 2020-07-19
      • 2016-07-31
      • 1970-01-01
      相关资源
      最近更新 更多