Laravel Array to Input checkbox true or false value - php

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.

Related

Laravel update multiple records by using checkbox

I have checkbox for all customers in blade.And i want to when i click here i change status.Now when i click checkbox it do all records status to 0 and new clicked statuses to 1.All old datas to 0.I dont want this.How i fix it.
It is controller sider
$clients = Client::all();
foreach ($clients as $client)
{
$client->is_slide_content = $request->has('is_slide_content.' .$client->id)? 1:0;
$client->save();
}
<td>
<input type="checkbox" name="is_slide_content[{{ $cs->id }}]" class="checkbox">
<label>{{trans('back.add')}}</label>
</td>
I hope I've understood what your issue is correctly.
When the data about the clients is being loaded their status (i.e. 'is_slide_content') is not taken into consideration thus all checkboxes are unticked. If you don't want the old values to change you should tell Blade that the ckeckbox should be checked by default by doing something like this:
<input type="checkbox" name="is_slide_content[{{ $cs->id }}]" class="checkbox" {{ $cs->is_slide_content == 1 ? 'checked' : '') }}>
Please note that you may need to modify the code a bit but the general idea is the same.
Also this is a related question and you may find something useful:
How to get checkbox value in a Laravel controller?

checkbox input always return null in Laravel 5.8

I recently using Laravel version 5.8, now I am little confused about how to input checkbox value to the table in the database, the checkbox value always return null, even the checkbox is selected, can anyone help me with this
by the way, this is my form checkbox
<form action="{{ $siswa->id_siswa}}/verifikasi">
#csrf
<label for=""><input type="checkbox" name="ijazah" id="" value="true">ijazah</label>
</form>
and this is my function in the controller
public function approve(Request $request,$id_siswa){
$ijazah = $request->ijazah;
dd($ijazah);
}
That is not how to get input from request.
For getting the input you should use
$data = $request->all();
That code will get all input request and store it to the array, after that you can get the ijazah input with:
$data['ijazah'];
Or if you only want to get 'ijazah' you can try this
$request->input('ijazah');

Store specific value in PHP

I am trying to store specific value in laravel. Here Select User not required field but in foreach loop hidden field proj_id must has value. Suppose there are 5 rows and I want to store only 2nd and 5th user along with proj_id from hidden field. Here I want to mention that in controller I also kept delete operation so that I can remove previously inserted SAME PROJECT ID related record. For example If I want to store 2nd and 3rd user, that time only 2nd and 3rd users record will remove first then insert. In my code there are logical error but could not find solution. Thanks in advance
<form action="{{ url('/save-project') }}" method="POST">
<tr>
#foreach($projects as $val)
<td>
<input type="hidden" name="proj_id[]" value="{{$val->id}}">
<select name="user_id[]">
<option value="">Select User</option>
<option value="2">x</option>
<option value="4">y</option>
</select>
</td>
#endforeach
</tr>
<input type="submit">
</form>
Controller
$countUserID = count($user_id);
assign_project::where('flag','Y')
->WhereIn('proj_id',$request->proj_id)
->delete();
for($i=0;$i<$countUserID;$i++){
$assign_project = new assign_project();
$assign_project->proj_id = $request->proj_id[$i];
$assign_project->user_id = $request->user_id[$i];
$assign_project->save();
}
JSON fields are gaining more popularity since they became officially supported in MySQL 5.7.8. Even the popular Spatie Laravel Medialibrary package use them, so why shouldn’t we?
To create a JSON field, all we need to do in Laravel migration is use ->json() method:
$table->json('array_data');
Next, you need to tell your model to cast that column from JSON to an array automatically:
class Product extends Model
{
protected $casts = [
'array_data' => 'array'
];
}
This way, you will receive $array_data as array and don’t need to do json_decode() at all.

Radio button in Laravel 5.4

I have a register form where users can sign up and I recently added two radio buttons to define users type.
Example:
(*) I want to buy (*) I want to sell
Here's how I was thinking to do this: I added a boolean field in the users table and I was thinking to check if I want to buy is checked then I store 1 in the database if the other one is checked then I store 0.
The thing is, I'm not sure how to check in the controller if the radio button is selected or not.. I tried to look in the documentation and on google but all I found were some ideas using the Form facade which as I know is no longer used in 5.4...
HTML
{{ Form::radio('result', 'buy' , true) }}
{{ Form::radio('result', 'sell' , false) }}
Without Form Facade
<input type="radio" name="result" value="buy" checked>
<input type="radio" name="result" value="sell">
Controller
$fields = Input::get('result');
if($fields == 'buy'){
// logic
}
else{
// logic
}
Remeber: Checkbox and radio button sends values on server end, if and only if they are marked as checked, if not checked that, then no values will be sent out to controller end. so you can do this check in your controller
eg:
public function myMethod(Request $request){
//2nd parameter means, if radio is not selected then use default value
$radio = $request->get('radion_button', 0);
}

How do I data bind to a checkbox input Laravel?

Using Laravel 5.1
I have a form that I am data binding to. Everything work as expected except for the checkbox.
Here is my input (blade template);
<input type="checkbox" name="noContact" value="{{ $profile['noContact'] }}">
The field is a boolean and the checked value should be 1. Doesn't seem to be binding. What am I missing?
Thanks!
Maybe try to use checked="checked" instead of value attribute :
<input type="checkbox" name="noContact"{{ $profile['noContact'] ? ' checked="checked"' : '' }}>
In your example if you set the value to "bla bla" and the checkbox is checked, when you send the form in the controller you will get exactly "bla bla".
If you want only to check if the checkbox is checked or not, just set the value to 1 and in the controller handle it like this:
$checked = (bool)Input::get("checkbox_name");
Or in a condition:
if(!empty(Input::get("checkbox_name"))){...}
In laravel, you can try to use Forms & HTML.
Form::checkbox( "noContact", $profile['noContact']);

Categories