I have multiple checkboxes, I want to display an array of data when multiple checkboxes are clicked, but only one value is displayed, how to display an array ?What is the problem?
<div class="form-group" >
<h5>Your languages</h5>
<div class="col-md-12">
#foreach($langs as $key => $lang)
<input type="checkbox" name="foo[]" value="{{$key}}">
<label>{{ $lang }}</label>,
#endforeach
</div>
</div>
To controller
public function Method(Request $request)
{
foreach((array)$request->input('foo') as $value){
$file = 'la.txt';
file_put_contents($file,$value );
}
return redirect()->route('profile');
}
I want to display the value of all these three checkboxes, but only the data of one of them is displayed
enter image description here
Hmm - let me guess the issue, I think that you should return the values while you return back to the profile view. I think also the problem is not in the first load of the profile view, because you have to pass the langs array, but the issue happens when you click the checkboxes to store the data in the controller's method, so your code must be like so
public function storeData(Request $request)
{
foreach($request->input('foo') as $value){
$file = 'la.txt';
file_put_contents($file, $value);
}
$yourLangsArray = ["English", "Arabic"];
return redirect()->route('profile')->with('langs', $yourLangsArray);
}
Related
Hi I have a row of data where I will like to allow the users to click on a checkbox on/off the data for use. I have read up on https://stackoverflow.com/a/43995087/14936674 answer and it is working fine, except that my checkbox value can only be update if it is checked. If I want to uncheck the box and update it, there will be no update done to it. Currently I have tested out just by updating the checkbox, however it will update and uncheck all of my data.
Below are my blade.php
<tbody>
#foreach($operatinghrs as $i => $operatinghr)
<tr id="{{ $operatinghr->{'opID'} }}">
<td>
<input type="hidden" name="operatinghrs[{{ $i }}][opID]" value="{{ $operatinghr->{'opID'} }}">{{ $operatinghr->{'day'} }}
</td>
<td>
<input type="time" id="start_time" name="operatinghrs[{{ $i }}][start_time]" min="00:00" max="23:59" value="{{ display24HTime(old('start_time', $operatinghr->start_time))}}">
</td>
<td>
<input type="time" id="end_time" name="operatinghrs[{{ $i }}][end_time]" min="00:00" max="23:59" value="{{ display24HTime(old('end_time', $operatinghr->end_time))}}">
</td>
<td>
<div class="switch">
<input type="checkbox" id="clinic_open" name="operatinghrs[{{ $i }}][clinic_open]" class="switch-input" value="1" {{ old('clinic_open', $operatinghr->clinic_open=="true") ? 'checked="checked"' : '' }}/>
<div class="circle"></div>
</div>
</td>
</tr>
#endforeach
</tbody>
Below are the codes in my controller class:
public function update(Request $request)
{
foreach($request->get('operatinghrs', []) as $operatinghr) {
$db = new OperatingHour();
$db->where('opID', $operatinghr['opID'])->where('clinic_id', '=', $_SESSION['clinic_ID'])
->update(
[
'clinic_open' => $request->input('clinic_open') ? true : false,
]
);
}
return back()->with('success_message', 'Details updated successfully!');
}
If you want to only update where $operatinghr['clinic_open'] value is true condition.
Consider this from MDN:
If a checkbox is unchecked when its form is submitted, there is no value submitted to the server to represent its unchecked state (e.g. value=unchecked); the value is not submitted to the server at all. If you wanted to submit a default value for the checkbox when it is unchecked, you could include an inside the form with the same name and value, generated by JavaScript perhaps.
Also you must access clinic_open value over $operatinghr as $operatinghr['clinic_open'] for specific entry. Not as $request->input('clinic_open')
So solution must like that:
// Get all Operating values.
$operatinghrs = $request->get('operatinghrs', []);
/*
* Filter values with clinic_open criteria.
* Checkbox values are only present when is checked.
* So isset control work for us.
*/
$operatingsForUpdate = array_filter($operatinghrs, function($op){
return isset($op['clinic_open']); // return only has clinic_open value.
});
// Loop for only for update operatings.
foreach($operatingsForUpdate as $operatinghr) {
// Update specific entry which contain clinic_open value is true.
}
Working with checkbox is always tricky, the default values of a checkbox are on and off, but if the checkbox is unchecked it won't appear in request data.
So you need to validate if the checkbox exists in request before try to update, and if not, save a string 'off' in the database or don't save anything and set a default value ('off') for that field, when you retrieve the data in the edit/update form, all the checkbox with 'off' value will be unchecked.
Using the has method on the $request, like this:
if($request->has('clinic_open')) {
foreach($request->get('operatinghrs', []) as $operatinghr) {
$db = new OperatingHour();
$db->where('opID', $operatinghr['opID'])->where('clinic_id', $_SESSION['clinic_ID'])
->update(['clinic_open' => $request->input('clinic_open')]);
}
}
Some advices:
Avoid using the '=' condition on where methods, laravel asummes it, save time and space.
Remove the value='1' of the checkbox, leave some work to the browser and do less.
in my show method in laravel i have a form that i want to submit and show the result on the same page so here is my show method first of all :
public function show(Property $property)
{
$property = Property::with('propertycalendars')->where('id', $property->id)->first();
foreach ($property->propertycalendars as $prop) {
$end_reserve = $prop->reserve_end;
}
// HERE NEW RELATION
$pdate = Property::with('dates')->get();
return view('users.properties.show', compact('property','pdate','end_reserve'));
}
and in the view of my show which for example is the url of a uniq property like below just as an example :
http://localhost:8000/properties/1
now i have a form to submit to search the Date table and bring me the dates so here is what i have wrote for the search function :
public function search (Request $request,$property_id){
//Send an empty variable to the view, unless the if logic below changes, then it'll send a proper variable to the view.
$results = null;
//Runs only if the search has something in it.
if (!empty($request->property_id)) {
$start_date = $request->start_date;
$search_date = Date::all()->where('date',$start_date);
}
return view('admin.properties.show')->with('search_date', $search_date);
}
and
thats my route :
Route::get('/properties/{{property_id}}','PropertyController#search');
and finally my form to submit the search :
<form action="/properties/search" method="get">
{{csrf_field()}}
<div class="row">
<div class="col-lg-5">
<input type="hidden" value="{{$property->id}}" name="property_id">
<input name="start_date" class="form-control m-input start_date" autocomplete="off"> </div>
<div class="col-lg-5">
<input name="finish_date" class="form-control m-input start_date" autocomplete="off"> </div>
<div class="col-lg-2">
<input type="submit" value="seach" class="btn btn-primary btn-block" autocomplete="off">
</div>
</div>
</form>
but now when i submit the form it returns a 404 not found with a link like below :
http://localhost:8000/properties/search?_token=R8ncSBjeZANMHlWMcbC6o5mYJZfwWgdfTwuviFo1&property_id=1&start_date=1398%2F1%2F12&title=
In your controller, change to the following:
public function search (Request $request){
//Send an empty variable to the view, unless the if logic below changes, then it'll send a proper variable to the view.
$results = null;
//Runs only if the search has something in it.
if (!empty($request->title)) {
$results = Property::all()->where('some search here')->get();
}
return view('admin.article.index')->with('results', $results);
}
This will send any (and all) results that your query finds to the view. Now in your view, you'll need to ensure there are actual results, or you'll get an error, so for example:
#if ($results)
//There are results, loop through them
#foeach($results as $item)
{{$item->title}}
#endforeach
#else
//There are no results, show the form maybe?
#endif
Without knowing your table structure, I can't give the exact way to loop through your results, but this should get you started.
Edit: Since OP's question nature changed a fair bit from the original question:
In order to achieve the new flow, you'd need to pass in a URL param in the route, and change it to be a get, since you're no longer posting it from a form:
Route::get('/properties/{search}','PropertyController#search');
This tells Laravel you've got something coming from a website.com/properties/xxxxx request - the xxxxx would contain the search key you'd then pass to your controller to lookup. The {search} portion in the route can be whatever name you want, just ensure the controller's second param matches it.
If you wanted to allow for a posting from your search form, you can (in addition) add the following to your routes:
Route::post('/properties','PropertyController#search');
Then in your controller, fetch whatever came from the form via the Request facade.
Then in your controller, you'd check if this is valid:
public function search (Request $request, $search){
//Send an empty variable to the view, unless the if logic below changes, then it'll send a proper variable to the view.
$results = null;
//Runs only if the second URL param has a value
if (!empty($search)) {
$results = Property::all()->where('some search here')->get();
}
return view('admin.article.index')->with('results', $results);
}
My dynamic drop down list is not working when I am trying to navigate to update page by using url id and then its showing errors.The result suppose to be a name of city that is associated with id in the database.
controller class
public function updateAddress($edit_id)
{
$data=[];
$data['edit_id']=$edit_id;
$address_data = $this->address->find($edit_id);
$data['first_name']=$address_data->first_name;
$data['last_name']=$address_data->last_name;
$data['street']=$address_data->street;
$data['zip_code']=$address_data->zip_code;
$data['city']=$address_data->city;
return view('update/edit',$data);
}
Here is my blade file. The rest of the fields are working properly except drop down list. I am using foreach loop to display data into the drop down list.
<select id="city" name="city" >
#foreach($data as $cities)
<option id="city" value="{{$cities->edit_id}}" selected="selected">{{$cities->city}}</option>
#endforeach
</select>
Update the code in the controller so that:
return view('update/edit',$data);
Is changed to:
return view('update/edit', ['data' => $data]);
change your controller code to
return view('update/edit',compact('data'));
and change your view page like
{{ $data['edit_id'] }}. you dont want to use #foreach.
I have an event and i want to add artists to it from artists table.
I want to do so by using a dropdown list where it need to get populated by artists name and their is a small '+' next to it to add other artists. Upon doing that a 3rd transitive table where event id and artist id should be inserted as foreign keys.
When I create the event
In my view:
<div class="form-group">
<label for="task-artist" class="col-sm-3 control-label">Artist:</label>
<div class="col-sm-6">
<select name="artist" id="artist" class="form-control input-sm">
<option value=""></option>
#foreach($artists as $artist)
{{$artist->stage_name}}
#endforeach
</select>
</div>
</div>
my controller:
public function index(Request $request)
{
return view('tasks.index', [
'tasks' => $this->tasks->forUser($request->user()),
'artists' => DB::table('artists')->pluck('stage_name', 'id'),
]);
}
public function show($id)
{
//Get results by targeting id
$task = Task::find($id);
//$artist = Artist::lists('stage_name', 'id');
//$artist = Artist::where('active', true)->orderBy('stage_name')->pluck('stage_name', 'id');
//
return view('tasks.show')->with('task',$task);
}
How shall i proceed ?
Please help.
Javascript is your friend here.
Let me write some steps that you can follow to achieve what you are looking for :
1) Have the Div tag and
2) use $.get() function in javascript to get the dynamic values from a controller.
3) $.each() to loop through the data and show it in select input field
4) on either selecting the value or clicking + button that you mentioned do another Javascript call to add the artist to the event.
Example :
HTML
<div class="uk-margin-bottom">
<div id="your select dropdown"></div>
</div>
JAVASCRIPT
$("#artist").change(function() {
getArtists();
});
function getArtist() {
var artist= $('#your div id');
artist.empty();
var code = '';
$.get("/url/" + variable_id, function(data) {
artist.empty();
console.log(data);// once you create route and controller you should see your artists lists here
code += '<label for="event_id" class="uk-form-label">Select Artist</label><select class="uk-width-1-1" name="artist_name" id="artist_name" value="select">';
code += '<option value="">Select Artists</option>';
$.each(data.artist, function(index, value) {
code += '<option value="' + value.artist_name+ '">' + value.artist_name + '</option>';
});
code += '</select>
artist.append(code);
});
}
have a form and add javascript to post artist to the controller and store data into events table. Try and see if you can achieve and follow my steps.
I am using codeigniter.When I perform add function I need to calculate tax. I have tax value in a table I need to fetch the value from the table and use it in my view page.
public function view()
{
$this->load->library('session');
$data['service_detail']=$this->session->userdata('service_detail');
$data['tax'] = $this->settings_model->get_tax();
$data['main_content'] = 'admin/service/view';
$this->load->view('includes/template', $data);
}
In model file I have this function by which I get the tax value from the table
public function get_tax()
{
$query = $this->db->query("SELECT company_tax13 FROM service_settings ");
$result = $query->result_array();
return $result;
}
Here is my view file where i get the tax value.
<div class="form-group">
<label for="email">Service price: <?=$service_detail['service_price']?> Rs</label>
</div>
<div class="form-group">
<label for="email">Tax Percentage : <?=$tax['company_tax13']?>%
<div class="form-group">
<?php
$tax_percentage=$tax['company_tax13'];
if(strstr($service_detail['service_tax'],"inclusive")==true) {
$taxamount=$service_detail['service_price']-($service_detail['service_price']/(1+($tax_percentage/100)));
$grand=$service_detail['service_price'];
}
else {
$taxamount=($service_detail['service_price']*(1+($tax_percentage/100)))-$service_detail['service_price'];
$grand=$taxamount+$service_detail['service_price'];
}
?>
<label for="email">Tax Amount : <?php echo $taxamount; ?> Rs</label>
<div class="form-group">
<label for="email">Grand Amount : <?php echo $grand; ?> Rs</label>
</div>
I could not get the tax value in my page.
Can someone help me. I do not know the reason why i get no value in my output.
Edit 01
In service_detail['service_price'] contains either inclusive or exclusive. with that value I use strstr() to compare that string.
use row_array() instead of result_array() because result_array() returns the first value in index 0 and you should call:
$tax[0]['company_tax13'];