Laravel - 5.8 explode not working for implode - php

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.

Related

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

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.

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>

Adding data to mysql table in ZF2

This is the code for add action, This action adds subjectName(from subjects Table), totalMarks and Description (from SubjectMarks Table)
public function addAction() {
$postArray = $this->params()->fromPost();
$entityManager = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
This if condition is set true if data is entered and addbutton is clicked
if (isset($postArray['submit']) && $postArray['subjectName']) {
$subjectMarks = new SubjectMarks();
$subjectMarks->setSubject(
$entityManager->find('Application\Entity\Subjects', $postArray['subjectName'])
);
$subjectMarks->setClasses(
$entityManager->find('Application\Entity\Classes', $postArray['classId'])
);
$subjectMarks->setSubject(
$entityManager->find('Application\Entity\Subjects', $postArray['subjectId'])
);
$subjectMarks->setTotalMarks($postArray['totalMarks']);
$subjectMarks->setDescription($postArray['subjectMarksDesc']);
$entityManager->persist($subjectMarks);
$entityManager->flush();
return $this->redirect()->toUrl($this->getRequest()->getBaseUrl().'/subjectmarks/totalmarks/index');
}
First else is executed that runs the query and sends data to 'add' view in form of 'data'
else
{
$entityManager = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
$qb = $entityManager->createQueryBuilder();
$qb->select(array(
'subjectMarks.subjectMarkId as subjectMarkId',
'subjectMarks.totalMarks as totalMarks',
'subjectMarks.description as subjectMarksDesc',
'subject.subjectId as subjectId',
'subject.name as subjectName',
'class.classId as classId',
))
->from('Application\Entity\SubjectMarks', 'subjectMarks')
->leftJoin('subjectMarks.subject', 'subject')
->leftJoin('subjectMarks.classes', 'class');
$data = $qb->getQuery()->getScalarResult();
return new ViewModel(array(
'data' => $data,
)
);
}
}
This is the code for add.phtml 'FORM' which is called when 'else' part executes and query selects the data required, and send the written data back, where it is received by if() condition.
<form name="myForm" action="<?php echo $this->url('subjectmarks/totalmarks', array('action'=>'add'));?>" method="POST">
<input type="hidden" name="classId" value="<?php echo $this->data[0]['classId'];?>">
<input type="hidden" name="subjectId" value="<?php echo $this->data[0]['subjectId'];?>">
<input type="text" name="subjectName" >
<input type="text" name="totalMarks" >
<input required="required" type="text" name="subjectMarksDesc" >
<button type="reset" class="btn btn-primary" > <a style="color: white" href="<?php echo $this->basePath('subjectmarks/totalmarks/index');?>">Cancel</a></button>
<button type="submit" name="submit" class="btn btn-success">Submit</button>
The Problem is that totalMarks and subjectMarkDesc are added correctly, while the subjectName is taken id[0] of subject table, for any name that is entered.
The answer is simple, as we can see that subjectName is inserted as input and subjectId is hidden, so there is no direct relation i.e, that clarify which subjectName is assigned to the subjectId.
So putting a select HTML tag will solve the problem, e.g
<select name="addSubjectMarks">
<?php foreach ($this->data as $item):?>
Here we can see subjectId and subjectName are related, unlike the question
<option value="<?php echo $item['subjectId'];?> "> <?php echo $item['subjectName'];?> </option>
<?php endforeach; ?>
</select>
Similarly there in the controller, inside the if (isset($postArray['submit']) && $postArray['subjectName']) condition, we will only replace this code
$subjectMarks->setSubject(
$entityManager->find('Application\Entity\Subjects', $postArray['addSubjectMarks'])
);
with this code
$subjectMarks->setSubject(
$entityManager->find('Application\Entity\Subjects', $postArray['subjectName'])
);
$subjectMarks->setSubject(
$entityManager->find('Application\Entity\Subjects', $postArray['subjectId'])
);
and it will perfectly. The select tag will output only those subjectNames which are already present in the subject Table.

Laravel 4 how do I keep checkbox checked after form is submitted

In part of my edit form I have check boxes. I can submit the form just fine, the values are stored in the database as comma separated values. So apple,microsoft etc. Which works fine but when I go back to the edit form the check boxes are not checked. I tried to echo out checked if the following was met:
<input name="software[]" type="checkbox" value="Ortho trac" <?php if(isset($_POST['software'])) echo "checked"; ?>> Ortho trac
But the above code doesn't work. I am not sure how to do it in laravel. Also when I try to update the values the previous values in the database disappear
The view
<div class="form-group mtop-20">
<label for="temp_software_experience">Software Experience:</label><br>
<label class="checkbox-inline">
<input name="software[]" type="checkbox" class="input-sm" value="Practiceworks"> Practiceworks
</label>
<label class="checkbox-inline">
<input name="software[]" type="checkbox" value="Softdent"> Softdent
</label>
<label class="checkbox-inline">
<input name="software[]" type="checkbox" value="Ortho trac" <?php if (isset($_POST['software'])) echo "checked"; ?>> Ortho trac
</label>
<label class="checkbox-inline">
<input name="software[]" type="checkbox" value="Dentrix"> Dentrix
</label>
<label class="checkbox-inline">
<input name="software[]" type="checkbox" value="Easy Dental"> Easy Dental
</label>
<label class="checkbox-inline">
<input name="software[]" type="checkbox" value="Practiceworks"> Eaglesoft
</label>
<label class="checkbox-inline">
<input type="checkbox" id="temp_software_experience" value="Other"> Other
</label>
</div><!-- end .form-group -->
The Controller
public function update($id)
{
// validate
// read more on validation at http://laravel.com/docs/validation
$rules = array(
'firstname' => 'required|min:3|alpha',
'lastname' => 'required|min:3|alpha',
'zipcode' => 'required|min:5|numeric',
'temp_experience' => 'required|min:1|max:50|numeric',
'temp_travel' => 'required|numeric',
'temp_hourly_rate' => 'required|numeric|min:10',
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if ($validator->fails()) {
return Redirect::to('user/profile/' . $id . '/edit')
->withErrors($validator)
->withInput();
} else {
$software_checked = Input::get('software');
if(is_array($software_checked))
{
$implade_software = implode(',', $software_checked);
}
// store
$user = User::find($id);
$user->firstname = Input::get('firstname');
$user->lastname = Input::get('lastname');
$user->zipcode = Input::get('zipcode');
$user->temp_experience = Input::get('temp_experience');
$user->temp_travel = Input::get('temp_travel');
$user->temp_hourly_rate = Input::get('temp_hourly_rate');
$user->temp_software_experience = $implade_software;
$user->save();
// redirect
Session::flash('message', 'Successfully updated profile!!');
return Redirect::to('user/profile/'.$id.'');
}
}
When you update you are redirecting afterwards thus clearing your POST data.
// redirect
Session::flash('message', 'Successfully updated profile!!');
return Redirect::to('user/profile/'.$id.'');
To access this data you will need to fetch it from your method of storage (database in this case), not your POST data as it contains nothing.
So that conditional should be something like:
<?php if(!empty($user->software)) echo "checked"; ?>
Note: You should be using Input::get() even within the view, no point in using $_POST.
Edit from comments:
The reason you are losing the data is because you first need explode() the data before you perform the conditional check against it.
Say you select:
[x] Apple
[ ] Orange
[x] Banana
In your column it would look something like apple,banana.
When you perform a conditional check it looks similar to this:
if ('apple,banana' == 'apple') echo 'checked';
You need to be checking if the an element within that comma delimited list exists. So try exploding it first and then checking it. This should be a good starting point.
$software = explode(',', $user->temp_software_experience);
Then for each input:
if (in_array("Practiceworks", $software)) echo "checked";
Here's the documentation for in_array().
Hope that clears some things up.

Categories