how to recuperate the value of the chosen option in checkbox with laravel? - html

I try to save the value of the chosen option of ckeckbox in database.
but I get always the value "on" saved in my database even I did not chose any option.
this is the code of answercontroller .
public function store(Request $request, Survey $survey)
{
// remove the token
$arr = $request->except('_token');
foreach ($arr as $key => $value) {
$newAnswer = new Answer();
if (! is_array( $value )) {
$newValue = $value['answer'];
} else {
$newValue = json_encode($value['answer']);
}
$newAnswer->answer = $newValue;
$newAnswer->question_id = $key;
$newAnswer->user_id = Auth::id();
$newAnswer->survey_id = $survey->id;
$newAnswer->save();
};
this is the view:
{!! Form::open() !!}
#if($question->question_type === 'text')
{{ Form::text('title')}}
#elseif($question->question_type === 'textarea')
<div class="row">
<div class="input-field col s12">
<textarea id="textarea1" class="materialize-textarea"></textarea>
<label for="textarea1">Provide answer</label>
</div>
</div>
#elseif($question->question_type === 'radio')
#foreach((array)$question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
<input type="radio" id="{{ $key }}" name="answer"/>
<label for="{{ $key }}">{{ $value }}</label>
</p>
#endforeach
#elseif($question->question_type === 'checkbox')
#foreach((array)$question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
<input type="checkbox" id="{{ $key }}" />
<label for="{{$key}}">{{ $value }}</label>
</p>
#endforeach
please help me , how can i get the value of the option. thanks in advance.

That is because you are not setting the value and name of checkbox
#foreach((array)$question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
<input type="checkbox" id="{{ $key }}" value="{{ $value }}" name="mycheck[]" />
<label for="{{$key}}">{{ $value }}</label>
</p>
#endforeach

Related

Many to many relationship Laravel 7

OrderController.php
public function create()
{
$user = Auth::user();
//shows only the dishes of the logged user
$dishes = Dish::orderBy("name", "asc")->where('user_id', Auth::id())->get();
return view("admin.orders.create", compact("dishes"));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validatedData = $request->validate([
"name" => "required|min:3",
"lastname" => "required|min:3",
"address" => "required",
"email" => "required",
"phone" => "required|min:8",
"total" => "required",
"dishes" => "required",
]);
$order = new Order();
$order->fill($validatedData);
$order->user_id = Auth::id();
$order->save();
//attach dishes to order
foreach ($request->dishes as $dish) {
$order->dishes()->attach($dish, [
"quantity" => $dish["quantity"],
"subtotal" => $dish["subtotal"]
]);
}
return redirect()->route("admin.orders.show", $order->id);
}
/**
* Display the specified resource.
*
* #param \App\Order $order
* #return \Illuminate\Http\Response
*/
public function show($id)
{
return view('admin.orders.show', [
'order' => Order::findOrFail($id)
]);
}
Order model
protected $fillable = [
"name", "lastname", "address", "email", "phone", "total", "user_id"
];
public function dishes()
{
return $this->belongsToMany('App\Dish')
->withPivot('quantity', 'subtotal');
}
I have a problem linking the orders table with the dishes one.
In the pivot table, I also have other columns to link.
What can I do to do this many-to-many relation?
The view I'm doing has the only purpose of trying to save the data into the pivot table.
View create.blade.php
{{-- quantity pivot table --}}
#foreach ($dishes as $dish)
<div class="form-group">
<label for="dish-quantity">Quantità di {{ $dish->name }}</label>
<input id="dish-quantity" type="number" name="dishes[{{ $dish->id }}]"
class="form-control #error('dishes') is-invalid #enderror"
placeholder="Inserisci la quantità" value="{{ old('dishes') }}">
#error('dishes')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
</div>
#endforeach
{{-- subtotal table --}}
#foreach ($dishes as $dish)
<div class="form-group">
<label for="dish-subtotal">Subtotale di {{ $dish->name }}</label>
<input id="dish-subtotal" type="number" name="subtotals[{{ $dish->id }}]"
class="form-control #error('subtotals') is-invalid #enderror"
placeholder="Inserisci il subtotale" value="{{ old('subtotals') }}">
#error('subtotals')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
</div>
#endforeach
{{-- total price --}}
<div class="form-group">
<label for="total_price">Prezzo totale</label>
<input id="total_price" type="text" name="total"
class="form-control #error('total') is-invalid #enderror" placeholder="Inserisci il titolo"
value="{{ old('total') }}" required>
#error('total')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
</div>

drop-down show selected value when editing a row laravel

<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>From Destination:</strong>
<select name="from_destination_data" class="form-control">
#if ($destinationsData != [])
#foreach($destinationsData as $info)
<option value="{{$destinationsData[$index]}}">{{$info}}</option>
#endforeach
#endif
</select>
</div>
</div>
I retrieve the $index of the selected $destinationData and when dd($destinationsData[$index]); I get the result that I need but it doesn't appear when I put it in the value as shown above
When constructing your <select> and <options>, you need to set a value for each that can be referenced when editing your record. See the following:
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>From Destination:</strong>
<select name="from_destination_data" class="form-control>
#foreach($destinationsData as $key => $info)
<option value="{{ $key }}">{{ $info }}</option>
#endforeach
</select>
</div>
</div>
Setting value="{{ $key }}" will, in this instance, set the value to a 0-based index, which can be referenced when editing:
#foreach($destinationsData as $key => $info)
<option value="{{ $key }}" {{ $record->from_destination_data == $key ? 'selected' : '' }}>{{ $info }}</option>
#endforeach
As long as $record->from_destination_data equals any of the $key iterations, that <option> will have selected="selected", setting it as the default selected option.

edit and update text area in php

my php function is not working when im add my text area in form. other all input or working. if im add remark(text area) in form edit function cant show text in that remark. other input is visible but i cant save it again
please help me to fined my error
Code before "html"
<?php
function renderForm($id, $vehicle_type, $duration, $amount,$remarks, $error)
{
?>
my HTML form
<form action="" method="post">
<div class="row">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div class="col-lg-4 col-xs-6" class="form-group">
<label>Vehicle Type <span style="color:red;font-size:8px;"><i class="fa fa-asterisk" aria-hidden="true"></i></span></label>
<select name="vehicle_type" class="form-control">
<option <?php echo ($vehicle_type=='Bicycle')?'selected':'' ?>>Bicycle</option>
<option <?php echo ($vehicle_type=='Bike')?'selected':'' ?>>Bike </option>
<option <?php echo ($vehicle_type=='Cars')?'selected':'' ?>>Cars </option>
<option <?php echo ($vehicle_type=='Truck')?'selected':'' ?>>Truck</option>
<option <?php echo ($vehicle_type=='Others')?'selected':'' ?>>Others</option>
</select>
</div>
<div class="col-lg-4 col-xs-6" class="form-group">
<label>Duration </label> <span style="color:red; font-size:8px; "><i class="fa fa-asterisk" aria-hidden="true"></i></span>
<input type="text" value="<?php echo $duration; ?>" name="duration" class="form-control" maxlength="20" placeholder="Eg: 4 Hrs">
</div>
<div class="col-lg-4 col-xs-6" class="form-group">
<label><i class="fa fa-inr" aria-hidden="true"></i> Amount</label> <span style="color:red;font-size:8px;"><i class="fa fa-asterisk" aria-hidden="true"></i></span>
<input type="number" name="amount" value="<?php echo $amount; ?>" class="form-control" placeholder="00">
</div>
</div>
<div class="row">
<div class="col-lg-4 col-xs-6" class="form-group">
<label>Remarks</label>
<textarea class="form-control" name="remarks" <?php echo htmlspecialchars($remarks); ?> rows="3" placeholder="Enter ..."></textarea>
</div>
<div id="butn" class="col-lg-3 col-xs-3">
<button class="myButton" type="submit" name="submit" value="Submit" class="btn btn-block btn-success btn-lg">SAVE</button>
</div>
</div>
</form>
Code after "html"
<?php
}
// connect to the database
include('connection.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
$vehicle_type = mysql_real_escape_string(htmlspecialchars($_POST['vehicle_type']));
$duration = mysql_real_escape_string(htmlspecialchars($_POST['duration']));
$amount = mysql_real_escape_string(htmlspecialchars($_POST['amount']));
$remarks = mysql_real_escape_string(htmlspecialchars($_POST['remarks']));
if ($vehicle_type=='' || $duration=='' || $amount=='' || $remarks=='')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $vehicle_type, $duration, $amount, $remarks, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE price_normal SET vehicle_type='$vehicle_type', duration='$duration', amount='$amount', remarks='$remarks', WHERE id='$id'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: pnormal.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM price_normal WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$vehicle_type = $row['vehicle_type'];
$duration = $row['duration'];
$amount = $row['amount'];
$remarks = $row['remarks'];
// show form
renderForm($id, $vehicle_type, $duration, $amount, $remarks,'');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
Take a look at the actual HTML in your browser. You're rendering the "remarks" content as an attribute of the textarea element:
<textarea class="form-control" name="remarks" <?php echo htmlspecialchars($remarks); ?> rows="3" placeholder="Enter ..."></textarea>
It should be the content of that element:
<textarea class="form-control" name="remarks" rows="3" placeholder="Enter ..."><?php echo htmlspecialchars($remarks); ?></textarea>

how to store drop-down list select into database?

I have a form for creating projects. It contains 2 foreign keys domain and owner (domain_id and owner_id). in fact these are 2 drop-down lists. when i try to submit the form, and check my database, I found out that owner and domain have NULL as value, eventhough i selected values from the drop-down list.
this is projectController :
public function create()
{
$domains = Domain::all('nameDomaine', 'id');
$owners = Owner::all('nameOwner', 'id');
return view('projectss.create', compact('domaines', 'owners'));
}
public function store(Request $request)
{
$domain_id = Domain::all()->pluck('nameDomain', 'id');
$owner_id = Owner::all()->pluck('nameOwner', 'id');
$this->validate($request, [
'title' => 'required',
'code' => 'required',
'domain_id' => 'required',
'owner_id' => 'required',
]);
Project::create($request->all());
return redirect()->route('projects.index')
->with('success', 'Project created successfully');
}
and this is create.blade.php :
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong> Domain : </strong>
<select class="form-control" name="domain_id">
#if (!count($domains) > 0)
<strong> Whoops! Something went wrong </strong>
#else
#foreach($domains as $id => $domain)
<option value="{{ $id }}">{{ $domain->domain }}</option>
#endforeach
#endif
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong> owner : </strong>
<select class="form-control" name="owner_id">
#if (!count($owners) > 0)
<strong> Whoops! Something went wrong </strong>
#else
#foreach($owners as $id => $owner)
<option value="{{ $id }}">{{ $owner->nameOwner }}</option>
#endforeach
#endif
</select>
</div>
</div>
I read a lot of posts about this problem, but none of them is working for me.
You can try this
in controller's store function
$domain_id = Domain::all('nameDomain', 'id');
$owner_id = Owner::all('nameOwner', 'id');
In you view
<select class="form-control" name="domain_id">
#if (!count($domains) > 0)
<strong> Whoops! Something went wrong </strong>
#else
#foreach($domains as $id => $domain)
<option value="{{ $domain->id }}">{{ $domain->domain }}</option>
#endforeach
#endif
</select>
and for second select option
<select class="form-control" name="owner_id">
#if (!count($owners) > 0)
<strong> Whoops! Something went wrong </strong>
#else
#foreach($owners as $id => $owner)
<option value="{{ $owner->id }}">{{ $owner->nameOwner }}</option>
#endforeach
#endif
You was not fetching id of your object. The $id you were fetching will just give you the index.
This should work :)
Change
#foreach($owners as $id => $owner)
<option value="{{ $id }}">{{ $owner->nameOwner }}</option>
#endforeach
to
#foreach($owners as $owner)
<option value={{ $owner->id }}>{{ $owner->nameOwner}</option>
#endforeach
And repeat with the other foreach loop.
If that doesn't work, in your controller add dd($request); to see what info is being passed to it and share with us, please.
Seems close but a few tweaks are needed. Also check your Project model and see if there is a $fillable array. If there is you'll need all the fields in your validate call in it e.g.
protected $fillable= [
'title'
'code'
'domain_id'
'owner_id'
];
Remove the calls in your store function.
public function create()
{
$domains = Domain::all('nameDomaine', 'id');
$owners = Owner::all('nameOwner', 'id');
return view('projectss.create', compact('domaines', 'owners'));
}
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'code' => 'required',
'domain_id' => 'required',
'owner_id' => 'required',
]);
Project::create($request->all());
return redirect()->route('projects.index')
->with('success', 'Project created successfully');
}
Make sure you're adding the right ID.
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong> Domain : </strong>
<select class="form-control" name="domain_id">
#if (!count($domains) > 0)
<strong> Whoops! Something went wrong </strong>
#else
#foreach($domains as $domain)
<option value="{{ $domain->id }}">{{ $domain->domain }}</option>
#endforeach
#endif
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong> owner : </strong>
<select class="form-control" name="owner_id">
#if (!count($owners) > 0)
<strong> Whoops! Something went wrong </strong>
#else
#foreach($owners as $owner)
<option value="{{ $owner->id }}">{{ $owner->nameOwner }}</option>
#endforeach
#endif
</select>
</div>
</div>

How to upload image file in Laravel?

I have a form which contains several fields including the upload file button that I want to use as an image uploader, (<input type="file" name="image" id="image" class='image'>). Other fields works fine and uploads everything on the database, however, in the image field, the filename of the file I uploaded is giving me this file name:
C:\laragon\tmp\php859A.tmp
... What should I do? Thank you: ) Here are the codes:
this is the form:
<html>
<div class="col-md-offset-4 col-md-4">
<form action="{{ $action }}" method="POST" enctype="multipart/form-data">
<h1> {{ $header }} </h1>
<div class="form-group">
<label for="exampleInputEmail1">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Name" value="{{ $name }}">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Description</label>
<input type="text" class="form-control" id="description" name="description" placeholder="Description" value="{{ $description }}">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Price</label>
<input type="number" class="form-control" id="product_price" name="product_price" placeholder="Price" value="{{ $product_price }}">
</div>
<div class="form-group">
<label for="image">SELECT IMAGE TO UPLOAD</label><br>
<input type="file" name="image" id="image" class='image'>
</div>
<div class="col-md-offset-2">
{!! csrf_field() !!}
<button type="submit" class="btn btn-default col-md-5" style="background:#0099ff; color:#f2f2f2;">{{ $button }}</button>
<button type="submit" class="btn btn-default col-md-5" style="background:#f4f4f4; color:#000;">Cancel</button>
</div>
</form>
</div>
</html>
These are my functions Create and Store in the controller:
public function create()
{
$data['action'] = route('beverage_store');
$data['button'] = 'Add';
$data['header'] = 'ADD BEVERAGE';
$data['name'] = old('name');
$data['description'] = old('description');
$data['product_price'] = old('product_price');
$data['image'] = old('image');
return view('layouts.beverages.beverageform',$data);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$input = $request->all();
#dd($input);
BeveragesModel::create($input);
return redirect()->route('beverages');
}
:)
Assuming you store the filename only on your database table, then you have to upload image somewhere else. So you could create something like:
private function upload($request)
{
$image_name = '';
if($request->hasFile('image'))
{
$image = $request->file('image');
$image_name = md5(uniqid()) . '.' . $image->getClientOriginalExtension();
$image->move(public_path() . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'beverages' . DIRECTORY_SEPARATOR, $image_name);
}
return $image_name;
}
public function store(Request $request)
{
$image_name = $this->upload($request);
$input = $request->all();
$beverage = BeveragesModel::create($input);
$beverage->image = $image_name;
$beverage->save();
return redirect()->route('beverages');
}