I'm getting some input from a dynamically generated form (I'm using jQuery to allow the user to add fields) using Input::all(). The field names are 'first_names[]', 'last_names[]' and 'emails[]'.
The $input variable now looks like this:
array (size=4)
'_token' => string '3VCQFUmAx8BNbSrX9MqjGtQhYovOaqecRUQSAL2c' (length=40)
'first_names' =>
array (size=1)
0 => string 'John' (length=4),
1 => string 'Jane' (length=4)
'last_names' =>
array (size=1)
0 => string 'Doe' (length=3),
1 => string 'Doe' (length=3)
'emails' =>
array (size=1)
0 => string 'johndoe@example.com' (length=24),
0 => string 'janedoe@example.com' (length=24)
What I want to do is create an array from that input that looks like this:
array (
0 => array(
'first_name' => 'John',
'last_name' => 'Doe',
'email' => 'johndoe@example.com'
),
1 => array(
'first_name' => 'Jane',
'last_name' => 'Doe',
'email' => 'janendoe@example.com'
)
)
Is there a simple way to do this without iterating over each array and building new ones? Is there a better way to generate the input? Thanks.
OK guys, with the help of alexrussell in Laravel IRC we've figured it out.
First thing is the JS:
var delegateId = 0;
$('.add-delegate').click(function() {
$.get('/add-delegate/' + delegateId++, function(html) {
$(html).appendTo('#delegates');
});
});
$(document).on('click', '.remove-delegate', function() {
$(this).parent().parent().remove();
});
We create a delegateId variable which we append to the get request URL and then in our routes.php we do:
Route::get('add-delegate/{id}', function($id) {
return View::make('admin.bookings.partials.add-delegate', compact('id'));
});
This sends the id to the view we use to generate the form fields. Then in the form we do:
<div class="row-fluid">
<div class="span12">
<input type="text" name="delegates[{{ $id }}][first_name]" placeholder="First Name">
<input type="text" name="delegates[{{ $id }}][last_name]" placeholder="Last Name">
<input type="text" name="delegates[{{ $id }}][email]" placeholder="Email">
<label class="checkbox">
<input type="checkbox" name="delegates[{{ $id }}][prerequisites]"> Prerequisites
</label>
<button type="button" class="btn btn-danger remove-delegate">Remove</button>
</div>
</div>
Once we get the input for delegates using:
Input::get('delegates')
We then have a nice array to work with, that is exactly what we're after:
array (size=2)
0 =>
array (size=3)
'first_name' => string 'John' (length=4)
'last_name' => string 'Doe' (length=3)
'email' => string 'johndoe@example.com' (length=19)
1 =>
array (size=3)
'first_name' => string 'Jane' (length=4)
'last_name' => string 'Doe' (length=3)
'email' => string 'janedoe@example.com' (length=19)