Reputation:
I'm trying to insert a data/value into my database.
It works but the problem is that every time I select the second value/checkbox only its other input value gets the value of the first input.
<form action="{{url('/reservation')}}" method="post">
@csrf
<div class="row col-12">
<div>
<p class='mybox text-dark'><input type="checkbox" name="prod_name[]" value="JasminBooks"/>JasminBooks</p>
</div>
<div>
<input type="number" name="prod_qty[]" min="1" value="1"class="form-control ml-2">
</div>
<div class="row col-12">
<div>
<p class='mybox text-dark'><input type="checkbox" name="prod_name[]" value="KnowHowBooks"/>KnowHowBooks</p>
</div>
<div>
<input type="number" name="prod_qty[]" min="1" value="1"class="form-control ml-2">
</div>
</div>
</form>
This is the code for my controller function
public function reservation(Request $request)
{
$data = new reservation;
$data->name = $request->name;
$data->email = $request->email;
$data->phone = $request->phone;
$data->address = $request->address;
$data->date = $request->date;
$data->time = $request->time;
$products = null;
$checked_array = $_POST['prod_name'];
foreach($_POST['prod_name'] as $key => $value) {
if (in_array($_POST['prod_name'][$key], $checked_array)) {
$products .= $_POST['prod_qty'][$key]." ".$_POST['prod_name'][$key].", ";
}
}
$data->products = $products;
$data->save();
return redirect()->back();
}
The result and the data is saved into the database when
What should I add/change in my code?
Upvotes: 0
Views: 990
Reputation: 2480
It's because you're defining your quantity fields based on index. If a single input is missing, it could throw off your whole result. Use the value as key:
HTML:
<div>
<p class='mybox text-dark'><input type="checkbox" name="prod_name[]" value="JasminBooks"/>JasminBooks
</p></div><div>
<input type="number" name="prod_qty[JasminBooks]" min="1" value="1"class="form-control ml-2">
</div>
PHP:
$products = '';
$checked_array = $request->input('prod_name', []);
$quantities = $request->input('prod_qty', []);
foreach ($checked_array as $value) {
if (array_key_exists($value, $quantities)) {
$products .= "{$quantities[$value]} {$value}, ";
}
}
// Remove trailing ', '
if (! empty($products)) {
$products = substr($products, 0, -2);
}
$data->products = $products;
P.S. Like Bhaumik said, don't use $_POST
in Laravel.
Upvotes: 1