Saving multiple checkbox value and different input value into database as one - php

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
I select the first checkbox and input a value of quantity 5 the result is "5 JasminBooks,"
When I select both checkboxes and input a value of quantity 12 in the first input beside the first checkbox and 7 for the second input/quantity besides the second checkbox the result is "12 JasminBooks, 7 KnowHowBooks, "
But when I only select the second checkbox and input a value of 13 for the quantity the result is "1 KnowHowBooks, " it takes the default value of the first input rather than the second input where I inserted 13 as the quantity.
What should I add/change in my code?

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.

Related

how to save checkbox value in array form?

How to save multiple checkbox value into database? now the value is storing in different rows. example: i selected value 1 and 2.so the value 1 in 1 row and value 2 in another row.
blade
<form enctype="multipart/form-data" action="/report/{{$postqs->id}}"
method="POST">
<input type="checkbox" name="item[]" value="one" />1
<input type="checkbox" name="item[]" value="two" />2
<input type="checkbox" name="item[]" value="three" />3
<div class="row">
<div class="form-group">
<label class="control-label col-sm-2"> Others:</label>
<div class="col-sm-7">
<textarea name="report" id="report" class="form-control"></textarea>
</div>
</div>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" class="pull-right btn btn-sm btn-primary">
</div></div></div>
</form>
Report model
protected $fillable = ['report','postqs_id','user_id','item'];
Store controller :
public function store(Request $request,Postqs $postqs,$id,Report $report,
Admin_report $admin_report)
{
foreach ($request->input("item") as $key=>$value){
$add_item = new Report;
$add_item->item= $value;
$add_item->user_id= Auth::user()->id;
$add_item->postqs_id=$id;
$add_item->save();
return back();
}
You should separate items as key and value so that you can save the value and the error it gives you shows that it needs user_id, so add the user_id to it., and your code should look like this:
foreach ($request->input("item") as $key=>$value){
$add_item = new Report;
$add_item->item= $value;
$add_item->user_id= Auth::user()->id;
$add_item->postqs_id=$id;
$add_item->save();
}
Because you want the value of the checkboxes, not the key. In the way you do it, it saves key and value together in the item column.
#Update
In this situation (saving array into DB) you don't put item input into foreach loop, and just save it as what it is, before that you must tell to your model to treat that as an array by putting $casts property into Report model:
protected $casts = [
'items'=>'array',
];
This way it should save as array into items column. after that you just save items like this code below:
$add_item = new Report;
$add_item->item= $request->input("item");
$add_item->user_id= Auth::user()->id;
$add_item->postqs_id=$id;
$add_item->save();
Note that there is no need for foreach loop in this scenario.
It seems you need to add user_id to insert a new Report.
$user = auth()->user();
foreach ($request->input("item") as $item){
$add_item = new Report;
$add_item->user_id= $user->id;
$add_item->item= $item;
$add_item->save();
}

how to save checkbox with multiple value in laravel 5.5

i'm having difficulty saving multiple item using checkbox, with this code i can only save one value at a time..can anyone give me idea
Controller:
$crud = explode(',', $request->crud_selected);
if (count($crud) > 0) {
foreach ($crud as $x) {
$slug = strtolower($x) . '-' . strtolower($request->resource);
$display_name = ucwords($x . " " . $request->resource);
$description = "Allows a user to " . strtoupper($x) . ' a ' . ucwords($request->resource);
$permission = new Permission();
$permission->name = $slug;
$permission->display_name = $display_name;
$permission->description = $description;
$permission->save();
}
Session::flash('success', 'Permissions were all successfully added');
return redirect()->route('permissions.index');
}
} else {
return redirect()->route('permissions.create')->withInput();
}
View-blade:
<script>
var app = new Vue({
el: '#app',
data() {
return:{
permissionType: 'basic',
resource: '',
crudSelected: []
}
}
});
</script>
<div class="from-group" v-if="permissionType == 'crud'">
<div class="checkbox-group" v-model="crudSelected">
<label class="checkbox-inline"><input type="checkbox" name="crud_selected" value="create">Create</label>
<label class="checkbox-inline"><input type="checkbox" name="crud_selected" value="read">Read</label>
<label class="checkbox-inline"><input type="checkbox" name="crud_selected" value="message">Update</label>
<label class="checkbox-inline"><input type="checkbox" name="crud_selected" value="message">Delete</label>
</div>
</div>
Any idea how to fix this.
I already manage to find answer this is what do i change the controller code.
Old
$crud = explode(',', $request->crud_selected);
New
$crud = $request->input('crud_selected');
then on my view-blade i add this to my
name="crud_selected[]
Wallahh it works..
if you want to take more than checked value on checkbox inputs, i think you can do it by define a function will call on each change event on your check box for example like this
<label class="checkbox-inline"><input type="checkbox" id ="checklval" name="crud_selected" v-model="crudSelected" v-on:change="trackcheck(Create)" :value="Create" >Create</label>
then on your vue component script you will implement this function,
i define array called ValArray will pushed on it each value selected on check box and will also pop from it if this value not checked on check box like this below :
trackcheck($labid) {
if(document.getElementById('checklval').checked==true){
this.ValArray.push($labid)
} else if(document.getElementById('checklval' ).checked==false){
this.ValArray.pop($labid)
}
}
now you will have an array with each selected value on check box inputs,
hope this help you
You don't need explode value, because the checkbox values returns array.
v-model is only used in input.
Form Input Bindings
<div class="from-group" v-if="permissionType == 'crud'">
<div class="checkbox-group" >
<label class="checkbox-inline"><input type="checkbox" v-model="crudSelected">Create</label>
<label class="checkbox-inline"><input type="checkbox" v-model="crudSelected">Read</label>
<label class="checkbox-inline"><input type="checkbox" v-model="crudSelected">Update</label>
<label class="checkbox-inline"><input type="checkbox" v-model="crudSelected">Delete</label>
</div>
</div>

Angular - storing checkbox values, and displaying them

Suppose that, you have 27 checkboxes, let's call them 'categories'. These checkboxes are in one section, you can select them multiple, and save.
The eseence is: if you save the form, the categories will be added to your profile, in MySQL.
My question is:
How I should name the models,
How I should store de values after sending the form
I had a solution for this, I saved the nth of the categories, then clicked them back at loading, but that's not the best.
Here is the code:
$scope.getSelectedCats = function() //Returning array: [1,4,5,6]
{
$return_array = [];
$i = 0;
if($scope.whoareu.develop){ $return_array[$i] = 1; $i++;}
if($scope.whoareu.design){ $return_array[$i] = 2; $i++;}
if($scope.whoareu.produce){ $return_array[$i] = 3; $i++;}
if($scope.whoareu.repair){ $return_array[$i] = 4; $i++;}
[...]
return $return_array;
}
HTML
<p>
<input ng-model="whoareu.develop" type="checkbox" value=1 id="WAY8" name="whoareu" />
<label for="WAY8">Develop</label>
</p>
<p>
<input ng-model="whoareu.design" type="checkbox" value=2 id="WAY9" name="whoareu" />
<label for="WAY9">Design</label>
</p>
<p>
<input ng-model="whoareu.produce" type="checkbox" value=3 id="WAY10" name="whoareu" />
<label for="WAY10">Produce</label>
</p>
<p>
<input ng-model="whoareu.repair" type="checkbox" value=4 id="WAY11" name="whoareu" />
<label for="WAY11">Repair</label>
</p>
[...]
And last, a very ugly solution for loading checks:
<?php
//$dbData = Data row from mysql, in object, by Wordpress
echo "setTimeout(function(){";
foreach(explode(',', $dbData->interested_in) as $val)
{
//echo "$('input:checkbox[name=whatareu]').filter('[value=$val]').click();";
echo "$('input:checkbox[name=whatareu]').eq($val-1).click();";
}
echo "}, 1000);";
?>
I don't know if I understand your problem well, see my snippet. If you want, you could create some mapping function setDefaultState(basedOn) which set checked in model checkboxs.
If the problem is that data is lost after you leave the controller, you should use some singleton storage like Angular's factories, and storage the checked categories there.
angular.module('app', [])
.controller('FrameController', ['$injector',
function($injector) {
var vm = this;
vm.checkboxs = [{
id: 'WAY8',
label: 'Develop',
checked: true
}, {
id: 'WAY9',
label: 'Design'
}]
angular.extend(vm, {
save: save
})
function save() {
// API call
console.log('checked: ', vm.checkboxs.filter(function(c) {
return c.checked
}).map(function(c) {
return {
id: c.id
}
}));
}
}
]);
setTimeout(function() {
angular.bootstrap(document.getElementById('body'), ['app']);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="body">
<div ng-controller="FrameController as vm">
<ul>
<li ng-repeat="checkbox in vm.checkboxs">
<input ng-model="checkbox.checked" type="checkbox" id="{{checkbox.id}}" name="whoareu" />
<label for="{{checkbox.id}}">{{checkbox.label}}</label>
</li>
</ul>
<button ng-click="vm.save()">
Save
</button>
</div>
</div>

Store values in database table using php explode function

I have a form with 4 or more checkboxes.The form is created by a while loop and has data from database table.Each checkbox represents a gift and each gift has a unique id (id1=1, id2=2, id3=3, ...) in database.So user can choose one or more gifts and click the submit button to store his choice.So I need php implode() function to get the string of what choices user made.For example if he chooses the 1st and the 2nd checkbox/gift the value that must be stored should be 1, 2.Instead of this I always have different stored data and don't match with user choices..Any ideas?
Form :
<form method='post' action='insert.php'>
.
.
.
while($row_select4 = $stmt_select4->fetch(PDO::FETCH_ASSOC)){
if($form_points>=$row_select4['points']) {
$points = $row_select4['points'];
echo '
<div>
<div class="feed-activity-list"><div style="border: 0.5px solid green; border-right-style:none;" class="input-group m-b"><span class="input-group-addon">
<input type="checkbox" onclick="enable_form();" id="checkbox" name="opt[]" value="'.$points.'"></span>
<input type="hidden" name="opt2[]" value="'.$row_select4['id'].'">
<div class="feed-element">
<a href="profile.html" class="pull-left">
<img alt="image" class="img-circle" src="'. $row_select4['image_url']. '">
</a>';
?>
<button type="submit" id="submit" name="eksasrgirwsh" class="btn btn-w-m btn-primary">ΕΞΑΡΓΥΡΩΣΗ</button>
</form>
Also (before insertion into table) :
if(isset($_POST['opt2'])){
foreach ($_POST['opt2'] as $value) {
$gift = $_POST['opt2'];
$sliced = array_slice($gift, 0, -1);
$gift_id = implode(", ", $sliced);
}
This is what I use to get the chosen gift_ids and create the string of them
Form updated:
<input type="hidden" disabled="disabled" name="opt2[]" value="'.$row_select4['id'].'">
Code for getting gift_ids:
foreach ($_POST['opt2'] as $value) {
$gift = $_POST['opt2'];
$gift_id = implode(", ", $gift);
}
No need for array_slice
in your php code:
$gift = $_POST['opt2'];
$gift_id = implode(", ", $gift);
By using this, you can get the result you wish.
Edit:
The reason you get all 1,2,3,4 is that you use hidden for gift id.
Try to add disabled="disabled" to the hidden tag which you dont want send to server. After this, you can get correct ids using $_POST['opt2']

Implode function doesn't store data as expected

I have already posted this but finally I didn't figure this out.I have a php form with some checkboxes (some of them are enabled and some disabled). Each of these has an id (id1=1, id2=2, id3=3, ...) which comes from database.
So when I submit the form I want to store these id's in a database table like this: if I choose only the 1st checkbox which has id=1 I should store '1' on my table and if I choose 1st and 3rd I should store '1, 3'. The problem is that I choose only the 1st and the stored data is '1, 2, 3, 4' because I have 4 checkboxes ENABLED.
PHP form :
<form method='post' action='insert.php'>
.
.
.
while($row_select4 = $stmt_select4->fetch(PDO::FETCH_ASSOC)){
if($form_points>=$row_select4['points']) {
$points = $row_select4['points'];
echo '
<div>
<div class="feed-activity-list"><div style="border: 0.5px solid green; border-right-style:none;" class="input-group m-b"><span class="input-group-addon">
<input type="checkbox" onclick="enable_form();" id="checkbox" name="opt[]" value="'.$points.'"></span>
<input type="hidden" name="opt2[]" value="'.$row_select4['id'].'">
<div class="feed-element">
<a href="profile.html" class="pull-left">
<img alt="image" class="img-circle" src="'. $row_select4['image_url']. '"
</a>';
?>
<button type="submit" id="submit" name="eksasrgirwsh" class="btn btn-w-m btn-primary">ΕΞΑΡΓΥΡΩΣΗ</button>
</form>
IMPLODE before insertion :
if(isset($_POST['opt2'])){
foreach ($_POST['opt2'] as $value) {
$gift = $_POST['opt2'];
$sliced = array_slice($gift, 0, -1);
$gift_id = implode(", ", $sliced);
}
And I store $gift_id in the table..
Check :
if(isset($_POST['opt'])){
$total_points = 0;
$points = array_values($_POST['opt']);
foreach ($points as $value) {
$total_points += $value;
}
echo $total_points;
$gift_ids = '';
$gift = array_keys($_POST['opt']);
foreach ($gift as $key => $value) {
$gift_ids = $value;
$gift_ids2 = implode(", ", $gift_ids);
}
echo $gift_ids2;
}
Instead of using separate hidden controls to store the ids, use the name property of the checkboxes to do this:
'...
<input type="checkbox" onclick="enable_form();" id="checkbox" name="opt['. $row_select4['id'].']" value="'.$points.'"></span>
...';
The name of a checkbox will be like name="opt[3]" for id 3 record.
In the php script processing the form submission array_keys($_POST['opt']) will give you the gift ids, while array_values($_POST['opt']) will return the points. You will know which point is associated with which gift id because the keys of the $_POST['opt'] are the gift ids.
Pls also note that storing multiple values in a comma separated string in a single field is not really considered a good practice. You should normalise your data structure and store the separate values in separate records.

Categories