Im getting an array within array of 'Cylinders' data from POST:
Array
(
[serie] => Array
(
[0] => 1234
[1] => 3545
)
[seriesap] => Array
(
[0] => 1234234
[1] => 345345
)
[type] => Array
(
[0] => 4546
[1] => csdfwe
)
[admission] => Array
(
[0] => 04-05-2015
[1] => 04-05-2015
)
[invoice] => Array
(
[0] => fei76867
[1] => feiasodjf
)
)
Now, the fields inside the keys: serie, type, admission, etc dont change, but the info inside those key do change, i mean there could be even 15 items in there.
At the end i need to save to the database:
$cylinder = new Cylinder();
$cylinder->serie = ??;
$cylinder->seriesap = ??;
$cylinder->type = ??;
$cylinder->admission = ??;
$cylinder->invoice = ??;
$cylinder->save
How can i accomplish this task and save all the cylinders?
I have tried all the foreach's that i could think of nothing seems to work.
/edit/
This is what Im doing so far:
$cyldata = $_POST['cylinder']; //this is the post from top.
$num_elements = 0;
while($num_elements < count($cyldata['serie'])){
$cylinder = new Cylinder();
$cylinder->serie = $cyldata['serie'][$num_elements];
$cylinder->type = $cyldata['type'][$num_elements];
$cylinder->admission = $cyldata['admission'][$num_elements];
$cylinder->seriesap = $cyldata['seriesap'][$num_elements];
$cylinder->save
$num_elements++;
}
But it feels ugly, all those saves doesnt feel right. Dirty solution if you ask me.
Because you are having an array to insert the data to database, you can try the
create
method from the model:but it actually needs the
key
of the array to be thefield_name
in your database. Or you can do this with the query builder:and again it is required to set the
key
of the array to be thefield_name
in your database.I don't know what forced you to use
$_POST
global array in order to receive the data from the user.Perhaps, this is what you want.
First, you need to convert you input data to another format:
Second, use the Fluent query builder to do a batch insert:
Note: the
created_at
andupdated_at
appear here if your table has these field. When working with Eloquent model, these field is updated automatically. However, we do not use Eloquent, so that we have to assign the value to these field manually.