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();
}
Related
I'm trying to insert two different value one is from a checkbox and one from different value such as quantity of the checkbox value beside it. I'm using foreach below as I am retrieving the books name saved into the database into the checkbox.
#foreach($data as $data)
<form action="{{url('/bookreservation')}}" method="post">
#csrf
<div class="row col-12">
<div>
<p class='mybox text-dark'><input type="checkbox" name="prod_name[]" value="{{$data->title}}"/>{{$data->title}}
<input type="number" name="prod_qty[]" min="1" value="1"class="form-control">
</div>
#endforeach
</div>
</form>
When I use the code below it successfully inserts the data into my database, however it only saves the prod_name since that is the only thing I implode and inserted to my database.
public function bookreservation(Request $request)
{
$data = new bookreservation;
$data->name=$request->name;
$data->email=$request->email;
$data->phone=$request->phone;
$data->address=$request->address;
$data->date=$request->date;
$data->time=$request->time;
$prod_qty = $request->prod_qty;
$selected_products = $request->prod_name;
$products = implode(" ",$selected_products);
$data->products=$products;
$data->save();
return redirect()->back();
}
When I try to implode it together it gives me an error that "implode() expects at most 2 arguments, 3 given"
$prod_qty = $request->prod_qty;
$selected_products = $request->prod_name;
$products = implode($prod_qty," ",$selected_products);
$data->products=$products;
and if I remove " " inside the implode a different error is given "implode(): Argument #1 ($separator) must be of type string, array given" because I want to save both as one value and be inserted into the database as one as well and not separately.
What should I do to save two different values into one. Where prod_qty is beside or before the selected_products like 32 JasminBooks and if they insert/select another different value like 5 KnowHowBooks the result will be "32 JasminBooks, 5 KnowHowBooks," in the database and both are not separated.
First of all, there seems mistake in html structure, you are using forEach loop, which has form inside it and it's end statement is before "form" end tag.
You may follow html structure something like this:
<form action="{{url('/bookreservation')}}" method="post">
<?php foreach ($content as $row):?>
<tr>
<td><input type="text" class="form-control" value="<?php echo $row['title']?>" name="title[]"></td>
<td><input type="text" class="form-control" value="1" name="qty[]"></td>
</tr>
<?php endforeach;?>
<button type="submit" name="submit" value="Submit">Submit</button>
</form>
Then on API controller you may do something like this to iterate over collection and insert record one by one into database:
for($i=0; $i<count($_POST[title]); $i++) {
if(isset($_POST[$i][title])) {
//here goes insert statement
}
}
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.
I did save computer field like implode.
A user cannot bid on a order more than once. If the user clicks on the order again, he should be prompted with a response page noting the user of having previously bid on the order.
$order = Order::where('user_id',auth()->id())
->explode( 'computer', request('computer'));
I create multiple checkboxes and I stored implode computer
order.blade.php
<form action="{{ route('store') }}" method="post">
<input type="checkbox" name="computer[]" value="1" id="hp">
<label for="hp">HP</label>
<input type="checkbox" name="computer[]" value="2" id="dell">
<label for="dell">DELL</label>
<input type="checkbox" name="computer[]" value="3" id="asus">
<label for="asus">ASUS</label>
<input type="checkbox" name="computer[]" value="4" id="acer">
<label for="acer">ACER</label>
<input type="checkbox" name="computer[]" value="5" id="sony">
<label for="sony">Sony</label>
<input type="checkbox" name="computer[]" value="6" id="fujitsu">
<label for="fujitsu">Fujitsu</label>
<input type="checkbox" name="computer[]" value="other_barnds" id="other_barnds">
<label for="other_barnds">Other</label>
<input type="submit" class="btn btn-primary" value="Save">
</form>
OrderController.php
public function store(Request $request)
{
$this->validate(request(), [
'computer' => 'required'
]);
$order = Order::where('user_id',auth()->id())
->where('computer', request('computer'))
->exists();
$order = new Order($request->all());
$order->user_id = auth()->user()->id;
$order->description = $request->description;
$computer = implode(",", $request->computer);
$order->computer = $computer;
$order->save();
if ($order) {
alert()->error('Warning', 'You ordered already');
return redirect()->back();
}
}
This code won't work, because computer field is a string and $request('computer') is an array.
$order = Order::where('user_id',auth()->id())
->where('computer', request('computer'))
->exists();
Also, as my comment above, you have to pass a csrf_token to submit the form. So use #csrf in your form tag.
Try below code, I have commented every step for better understanding.
public function store(Request $request)
{
$this->validate(request(), [
'computer' => 'required'
]);
//Now fetch the user's computer record, it will give you a string.
$users_computers = Order::where('user_id',auth()->id())->get('computer');
//convert this string to array
$users_computers = explode(',',$users_computers);
//Now check if there is at least one order is common or exists
$common_orders = array_intersect($users_computers, $request['computer']);
//throw error if any orders exists already
if(count($common_orders)>0)
{
alert()->error('Warning', 'You ordered already');
return redirect()->back();
//To give which computers user have orders you can access $common_orders values.
}
$order = new Order();
$order->user_id = auth()->user()->id;
$order->description = $request->description;
$computer = implode(",", $request->computer);
$order->computer = $computer;
$order->save();
return redirect()->back();//pass here a success message if you want
}
Use eloquent relationship to fetch and store a user's orders more conveniently.
I am trying to make a random tournament generator, where I can select names from a list with checkboxes and then randominze them into a different order.
I have the following form:
<form method="post" action="<?php echo ROOT ?>HomeController/createTournament/" enctype="multipart/form-data">
<div class="form-group">
<label for="participants">Select participants</label><br>
<?php foreach($players as $p): ?>
<input type="checkbox" name="participants" value="<?php echo $p['name'];?>"> <?php echo $p['name'];?><br>
<?php endforeach; ?>
</div>
<button type="submit" class="btn btn-primary btn-block" name="create">Show participants</button>
</form>
This form show's a checkbox and behind the checkbox the name of the participant.
This is my method:
public function createTournament() {
if(isset($_POST["create"])) {
$participants = $_POST['participants'];
}
include('app/views/showTournament.php');
}
That means I am saving the checked ones into $participants, right?
In the file showTournament, I know have access to $partipants.
I try to var_dump $particpants and it shows me:
string(6) "Onlyoneselected name"
So I tried a foreach, to get ALL of the selected names.
<?php
foreach($participants as $p) {
echo $p;
}
;?>
The foreach isn't showing anything, but the file has access to $participants. I want all the names on my screen, so I can start randomizing them. What do I do wrong?
<input type="checkbox" name="participants"
This line here is the root of your problems.
Because every checkbox has the same name, the value of $_POST['participants'] gets overridden for each checkbox in the list.
If you change that snippet to:
<input type="checkbox" name="participants[]"
Then $_POST['participants'] becomes an array of all checked values.
You need multiple checkbox values.
And therefore, HTML name of the input should be multiple (array)
<input type="checkbox" name="participants" will return string, only latest submitted value.
<input type="checkbox" name="participants[]" will return array of all submitted values.
So, replacing name="participants" to name="participants[]" will work.
I need to save multiple checkbox to single field in the database.
<div class="checkbox">
<label>
<input type="checkbox" name="expresion_vegetal_id[]" value="1">Raíz
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="expresion_vegetal_id[]" value="3">tronco
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="expresion_vegetal_id[]" value="4">corteza
</label>
</div>
Controller:
$ficha_tecnica = new Ficha_Tecnica();
$options = $request->get('expresion_vegetal_id');
$ficha_tecnica->expresion_vegetal_id = $options;
$ficha_tecnica->save();
this is trying to save, the values in [""], I need only save the numbers
insert into `fichas_tecnicas` (`expresion_vegetal_id`) values (["1","3","4"])
When I try to save, show the next message
1366 Incorrect integer value: '["1","4"]' for column 'expresion_vegetal_id'
You'r cannot add that because
You can try to loop the expresion_vegetal_id still in array format.
I see in your question is you need to add that in string format.
You must loop that array first and save one by one or you can used created
I give you the sample using loop.
You code will looks like this
$ficha_tecnica = new Ficha_Tecnica();
foreach ($$request->expresion_vegetal_id as $expresion_vegetal_id) {
$ficha_tecnica->fresh();
$ficha_tecnica->expresion_vegetal_id = $expresion_vegetal_id;
$ficha_tecnica->save();
}
i hope you can find the other same way....