user2073511
user2073511

Reputation: 13

Laravel - How can I post array of objects?

I have a dynamic table, where I can add and delete rows. In each row, there are some inputs where the user can add data to an object.

Right now, I am hardcoding each index number to the name attr. Like this:

<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]">

Is it possible to do something like this:

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

And receive the request just like when it was hardcoded indexes?

I need to post multiple objects to the store method in the controller. When I receive the request, I want the data to be like this without hardcoding the indexes.

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

Thanks in advance.

Upvotes: 1

Views: 3877

Answers (1)

Edwin Krause
Edwin Krause

Reputation: 1806

Option number 2 is not possible, that will result in something like this:

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

So when adding dynamically your fields you need to add them with the numbers for each set:

Lets assume this is your form

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

Using jQuery that could be something like that:

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]">';
}

Upvotes: 2

Related Questions