I come here requesting some help with the logic of this case, and if possible, some help with the code as well.
So here's the thing. Let's assume I have these two tables, which of course, have a One-Many relationship:
*These aren't the real tables, they're just to simplify things*
**Table books**
id
name
**Table books_reviews**
id
books_id
user_id <-this would be the person who wrote a review
details <-A varchar 140 field
rating <-A 1 through 10 integer field
Ok now. What I want to do is create a link, that will just append one more row to a table with the whole form. Like so...
The HTML
<a href="#" id="myLink">Write one more review</a>
<table id="mytable">
</table>
<input type="submit"> <- This should sumbit all the rows for validation and insertion
The Javascript
$(document).ready(function(){
var click=0;
$('#myLink').click(function(){
click++;
$('#mytable').append('<tr>
<td><input type="text" class="form-control" id="details'+click+'" name="details'+click+'"</td>
<td><input type="text" class="form-control" id="rating'+click+'" name="rating'+click+'"</td>
</tr>');
});
});
Ok, so I think this is pretty clear. Of course I would also append the specific reviews id to each row, but i didn't think it would be necessary to do that here.
The thing is I cant figure out what to do PHP-wise. What to write in my controller so that it will detect all the rows and create the arrays for the data in each row, then validate and insert it. Could anyone give me a hand with this?
If you look at the source code generated by your javascript, you should see that the names of your inputs would be like:
This is probably not the best option, I recommend you name all your inputs like
details[]
andrating[]
. There's no need to use the counter.Like you probably know, in laravel you should use Input::all() to get all the form data. This function should return to you the following array:
To insert multiple rows at once with laravel you can use the function
BookReview::insert($array)
, this function receives an array of arrays to be added in the database. This array should be like this one:So, all you have to do is convert the array 'form data' to the array 'eloquent ready'. This can be done with a simple algorithm:
PS: In my examples I did not add the other fields, like user_id and book_id. You should add it on the foreach to add this info into all rows.