Passing checkbox value from view to controller - laravel

How to pass checkbox value from views to controller so that I can compare the checked/unchecked values (for database update)?
Views:
#foreach ($second as $sec)
<br>
<div class = "form-group">
{{$sec->Roll }}
&nbsp&nbsp&nbsp&nbsp
{{ $sec->Name}}
</div>
<div class = "form-group">
<input tabindex="1" type="checkbox" value="{{$sec->Roll}}" name="1" />
</div>
#endforeach
Controller:
foreach ($columns as $col) {
//dd("Y");
if($col == $txt[1]) {
$got=DB::table($req)->select($col)->get();
//dd($got);
//COMPARE CHECKBOX VALUE "CHECKED/UNCHECKED" WITH ITS DEFAULT VALUE
DB::statement("UPDATE " . $req . " set " . $got . " to " . $got . " + 1 WHERE" .$req->Roll . " IN ".( implode(',', $req)));
}
}

Ps: This might be applicable only if my description matches what you are trying to do, because your question seems so.
One of the ways I have done it is not to put any value in the checkbox element. Then inspect if the value returned is string with is_string($the_variable) or not. That is, instead of:
<input tabindex="1" type="checkbox" value="{{$sec->Roll}}" name="checkbox_1" />
I'll have:
<input tabindex="1" type="checkbox" name="checkbox_1" />
This might not be an ideal solution, but a bit curious if you have tried it.
So in the controller, any checked checkbox would have 'on' as the value, while unchecked one would have null:
so if I do in my controller:
return request()->all();
I should get the values of the checked as 'on' and the values of the unchecked as null
So i'll do for example in controller:
if(is_string(request()->get('checkbox_1))) {
//checked
else {
// unchecked
}
Hope this is clear now.
Just for an update:
One other way to do this is to pass the key of the column you are trying to update when making the foreach, so you will have something like this:
#foreach ($second as $key=> $sec)
then on the checkbox it will serve as different names:
<input tabindex="1" type="checkbox" name="{{ $key }}" />
This way if you do return request()->all(); at the first in your controller, you can then tell if something else is wrong or not.
Please make sure you note the $key in that foreach() so to be sure you are doing the right thing.

Related

Undefined variable $attendance_status using radio button laravel

i am using laravel query builder but the problem is i am using radio buttons but i want to update the attendance at the radio button but it returns an error Undefined variable $attendance_status
i don't know why please help and how can i pass the $attendance_status variable
here is my code
my form
<form action="{{route('Attendances.update',$student->id)}}" method="post">
#csrf
#method('PUT')
<input type="hidden" name="id" value="{{$student->id}}">
<label class="block text-gray-500 font-semibold sm:border-r sm:pr-4">
<input name="attendences"
{{ $student->attendances()->first()->attendence_status == 1 ? 'checked' : '' }}
class="leading-tight" type="radio" value="presence">
<span class="text-success">حضور</span>
</label>
<label class="ml-4 block text-gray-500 font-semibold">
<input name="attendences"
{{ $student->attendances()->first()->attendence_status == 0 ? 'checked' : '' }}
class="leading-tight" type="radio" value="absent">
<span class="text-danger">غياب</span>
</label>
<div class="modal-footer">
<button type="button" class="btn btn-secondary"
data-dismiss="modal">{{trans('Students_trans.Close')}}</button>
<button class="btn btn-danger">{{trans('Students_trans.submit')}}</button>
</div>
</form>
here is my controller
update
public function update(Request $request, $id)
{
// return $request;
if($request->attendances == 'absent'){
$attendance_status = 0;
}
else if($request->attendances == 'presence'){
$attendance_status = 1;
}
Attendance::find($id)->update([
'student_id'=> $id,
'grade_id'=> $request->grade_id,
'class_id'=> $request->classroom_id,
'section_id'=> $request->section_id,
'attendance_date'=> date('Y-m-d'),
'status' => $attendance_status,
]);
return back();
You have an if and an elseif in your Controller, so only 2 conditions would create a variable named $attendance_status. You probably want to add a default branch, else basically, to make sure that the variable gets created with some default value before you try to use it in your update call.
Not sure which one of those 2 options you want to be the default but this would simplify things:
$attendance_status = $request->attendences == 'presence';
https://laravel.com/docs/9.x/redirects#redirecting-with-flashed-session-data
You may use the withInput method provided by the RedirectResponse instance to flash the current request's input data to the session before redirecting the user to a new location. Once the input has been flashed to the session, you may easily retrieve it during the next request:
return back()->withInput();
Surely {{ $student->attendances()->first()->attendence_status == 0 ? 'checked' : '' }} logic does not work in this way.
try this instead
<input name="attendences" checked="{{ $student->attendances()->first()->attendence_status == 0 ? true : false}}" class="leading-tight" type="radio" value="absent">

File upload with multiple browse button (populated from array) on Laravel

I need to upload file from dynamic upload button that generated form array as below code (Edited and workd already).
#foreach( $transfer as $key => $item )
<tr>
<td>
<input type="file" name="document[]" class="doc filestyle"/>
</td>
</tr>
#endforeach
This is boostrap filestyle
<script type="text/javascript">
$('.doc').filestyle({
buttonName : 'btn-success',
input: false,
icon: false,
});
It only work for single file. But I have no idea for multiple. (Edited and workd already)
if(count(Request::file('document', [])) > 0){
foreach( Request::file('document', []) as $key => $item ){
echo 'Reg ID: ' . $key . '<br />';
echo 'Value: ' . $item->getClientOriginalName() . '<br />';
}
}
Thanks for all advise.
Thats because you are not defining your control name as array
Change This to
<input type="file" name="document" id="doc{{$key}}" class="filestyle"/>
This
<input type="file" name="document[]" id="doc{{$key}}" class="filestyle"/>
Not name="document" change to name="document[]"
and sorry i have missed multiple Attributes in tag thanks to #Md.Sukel Ali
This Might Work
You need to add multiple attribute in your in input field.
<input type="file" name="document[]" id="doc{{$key}}" class="filestyle" multiple="" />

Issues with radio button in laravel

i want to set the radio button in the form using controller
( note: no database included).
And i even have no idea how to set the radio
button in the form using controller .
{this is my radio button}
<div class="row">
<div class="col-25">
<label for="gender">Gender</label>
</div>
<div class="col-75">
<input type="radio" name="gender" value="male" > Male
<input type="radio" name="gender" value="female"> Female
</div>
</div>
this is my controller :
class NewController extends Controller
{
public function index(Request $request)
{
$fullname='sagar basnet';
$subject='this is my test form';
return view('newfile/forms')
->withFullname($fullname)
->withSubject($subject);
}
I am going make a best effort to answer your question as their is no sample code provided.
I am assuming that you want to set the state of a radio button in the UI based on conditions that occur within your controller logic.
In your controller..
$radioVal = false;
if ($condition) {
$radioVal = 'checked';
}
return view('your.view', [
'radioVal' = $radioVal;
]);
The condition is the condition that determines whether or not your radio is checked (e.g. apples = fruit)...
In your view...
<input type="radio" {{ $radioVal or 'checked' }} />
The "or" keyword in blade offers you a ternary shorthand alternative.
You will need to give your radio button a name obviously...

Error retrieving a checked Checkbox in Laravel as a boolean

I'm a bit new to laravel and I'm working on a laravel application which has a checkbox field which should have a boolean value of 1 when the user checks the checkbox, and 0 when the checkbox is unchecked.
I want to retrieve the boolean value as either 1 or 0 and save in a db.
Please assist?
View
<form method="POST" action="{{ route('b2c.getplans') }}" id="travel_form" accept-charset="UTF-8">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="check-now {{ $errors->has('spouse') ? ' has-error' : '' }}">
<h1 class="cover-travel">I am travelling with</h1>
<label class="spouse-me">
<h1 class="pumba">Spouse</h1>
<input id="spouse" type="checkbox" name="spouse">
<span class="checkmark" name="spouse"></span>
</label>
#if ($errors->has('spouse'))
<span class="help-block">
<strong>{{ $errors->first('spouse') }}</strong>
</span>
#endif
</div>
<button type="submit" class="form-b3c"> Get Plans</button>
</form>
Controller
public
function validatePlanEntries(Request $request)
{
$validation = $this->validate($request, [
'WithSpouse' => (\Input::has('spouse')) ? 1 : 0;
]
}
1st way is send correct value from frontend side
you can add jquery or javascript at frontend side on change event of checkbox :
<input type="checkbox" name="checkbox" id="myCheckbox" />
<script>
$(document).on('change','#myCheckbox',function(){
if($(this).is(':checked')){
$('#myCheckbox').val(1);
}else{
$('#myCheckbox').val(0);
}
});
</script>
at your backend side , now you can check :
$yourVariable=$request->input('checkbox');
2nd way is only check at your backend
you will get your checkbox value=on if it checked
if($request->input('checkbox')=='on'){
$yourVariable=1;
}else{
$yourVariable=0;
}
you can use ternary condition as well , like :
$yourVariable = $request->input('checkbox')=='on' ? 1:0;
You don't have to validate a checkbox value. because if its checked it sends the value of on, and if it's not checked it doesn't send anything.
So, all you need is that get whether the check box is checked or not, you can do as follow.
to retrieve the boolean value of the checkbox,
Controller
// since you haven't provide any codes in the controller what
// are you gonna do with this value,
// I will juts catch it to a variable.
$isChecked = $request->spouse == 'on'
To retrieve checkbox value from request as boolean:
$yourModel->with_spouse = (bool) $request->spouse;
If checkbox is checked then it's value (on by default) will be passed to request and casting non-empty string to boolean will give you true. If checkbox is not checked then spouse key won't be passed to request at all, so $request->spouse will return null. Casting null to boolean will result in false (in PHP true is int 1 and false is int 0, which is exactly what you want).

retrieving user input in code igniter but not getting the value inside a foreach loop

I am working with code igniter and got stuck when i compare the user input with the already existing values in database. I have a form from where i get a user input. The form is as follows:
<form method="post" action="my_controller/my_method">
<label>Mark :</label>
<input type="text" name="avg_mark"><br>
<label> Message </label>
<input type="text" name = "message"><br>
<input type="submit" class="btn btn-info" value="send message">
</form>
In my_controller/my_method
function my_method{
$avg_mark =$this->input->post('avg_mark');
$message = $this->input->post('message');
echo $avg_mark;
}
when i echo $avg_mark iam getting the value. But problem arises when i take that value inside a foreach loop.
foreach($students as $row){
echo $avg_mark;
}
the page is blank and shows nothing which means iam not getting the input value inside the loop. And i tried this too inside the loop. Still the result is same.
foreach($students as $row){
echo $this->input->post('avg_mark');
}
What should i do to get the value inside a foreach loop.
First check that variable empty or not. Then you pass it in to foreach loop:-
if (!empty($students)) {
foreach($students as $row){
echo $avg_mark;
}
}

Resources