Save multiple checkbox values and different input values as a whole to the database
P粉807471604
2023-08-31 11:17:47
<p>I'm trying to insert data/values into my database. </p>
<p>It works, but the problem is that every time I select only the second value/checkbox, its other input values get the value of the first input. </p>
<pre class="brush:php;toolbar:false;"><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></pre>
<p>This is the code for my controller function</p>
<pre class="brush:php;toolbar:false;">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();
}</pre>
<p>When</p>
<ol>
<li>When I select the first checkbox and enter a value of 5, the result is "5 JasminBooks,"</p><p></li>
<li>When I select both checkboxes and enter the quantity 12 in the first input box next to the first checkbox and the second input box next to the second checkbox When the quantity is 7, the result is "12 JasminBooks, 7 KnowHowBooks," </li>
<li>But when I only select the second checkbox and enter 13 in the quantity input box, the result is "1 KnowHowBooks," which takes the default value entered in the first instead of what I entered in the second Insert the quantity 13 into the input box. </li>
</ol>
<p>What should I add/change in my code? </p>
This is because you define your quantity field based on the index. If one input is missing, it can affect your entire results. Use values as keys:
HTML:
PHP:
P.S. Like Bhaumik said, don't use
$_POST
in Laravel.