Undefined variable $attendance_status using radio button laravel - 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">

Related

foreach error laravel multiple checkbox store

I store a few checkboxes as array in Laravel, but I get an error on Foreach. Can someone help me?
in model
public function setHandServiceAttribute($value)
{
$this->attributes['handservice'] = json_encode($value);
}
public function getHandServiceAttribute($value)
{
return $this->attributes['handservice'] = json_decode($value);
}
in checkbox
<div class="form-check mx-3">
<input class="form-check-input" type="radio" id="1" value="کاشت" name="handservice[]">
<label class="form-check-label" for="1">کاشت</label>
</div>
<div class="form-check mx-3">
<input class="form-check-input" type="radio" id="2" value="کاور" name="handservice[]">
<label class="form-check-label" for="2">کاور</label>
</div>
handservice is column of reservation table in database with value like this after store
["\u062a\u0631"]
and in view
#forelse($reservation->handservice as $hand)
{{ $hand }},
#empty
nothing
#endforlse
error
json_decode(): Argument #1 ($json) must be of type string, array given
I used this article but I get an error when one of the columns handservie is empty handservice in nullable
https://hackthestuff.com/article/how-to-store-multiple-checkbox-value-in-database-in-laravel8
It finally worked
in model
public function getHandServiceAttribute($value) {
return json_decode($value);
}
in view
#if($reservation->handservice != null)
#forelse($reservation->handservice as $hand)
{{$hand}},
#empty
نا مشخص
#endforelse
#else
<p class="text-danger">انتخاب نشده</p>
#endif
thanks all
You shouldn't try to assign something in a getter.
public function getHandServiceAttribute()
{
return json_decode($this->attributes['handservice']);
}

Error message "The GET method is not supported for this route. Supported methods: POST." in laravel 8

Following is my controller. Method ProjectsView is to view all the listings. The second method BackendProjectSearch is for searching of projects. The first page of search result is displayed properly, but when we click on next page it gives the error "The GET method is not supported for this route. Supported methods: POST."
What should I do ?
public function ProjectsView(){
$projects = projects::orderBy('id','ASC')->paginate(15);
return view('backend.projects.projects_view',compact('projects')); }
public function BackendProjectSearch(Request $request){
$request->validate(["search" => "required"]);
$item = $request->search;
$projects = Projects::where('project_name','LIKE',"%$item%")->paginate(15);
return view('backend.projects.projects_view',compact('projects')); }
Following are the routes for both the methods :
Route::post('/backend/project/search', [ProjectsController::class, 'BackendProjectSearch'])->name('backend.project.search');
Route::get('/view', [ProjectsController::class, 'projectsView'])->name('projects.view');
View code :
<div class="col-md-8">
<div class="header-navsearch">
<form class="form-inline mr-auto" method="post" action="{{route('backend.project.search')}}">
#csrf
<div class="nav-search">
<input type="search" name="search" class="form-control header-search" placeholder="Search projects…" aria-label="Search">
<button class="btn btn-primary" type="submit"><i class="fa fa-search"></i></button>
</div>
</form>
</div>
</div>
The route for this request should be post, not get.
Example
Route::post(-----);
Also, make sure to insert a CSRF token while making the request
it means you now cannot do something like the following.
Instead, you have to do something like...
<form action="{{ route('example') }}" method="POST">
#csrf {{-- According to the version of laravel --}}
{{-- Your other codes --}}
<button type="submit" class="">Submit</button>
</form>
You have to use the below code
return redirect()->route('projects.view')->with(['projects' => $projects]);
Your route might be little change
Route::get('/view/{projects?}', [ProjectsController::class, 'projectsView'])->name('projects.view');
and In your controller, you have to change function like this
public function ProjectsView($projects = null){
if($projects!=null){
return view('backend.projects.projects_view',compact('projects'));
}
else{
$projects = projects::orderBy('id','ASC')->paginate(15);
return view('backend.projects.projects_view',compact('projects'));
}

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).

How do I bind a radio button value to my model? Laravel 5.3

I have a form with a couple of radio buttons;
<div class="form-group{{ $errors->has('procurement') ? ' has-error' : '' }} col-md-6">
<label for="procurement" class="col-md-6 control-label">Procurement Type <span class="red">*</span></label><br>
<div class="col-md-12">
<input id="procurement" type="radio" name="procurement" value="owned"> Owned
<input id="procurement" type="radio" name="procurement" value="rental"> Rental
#if ($errors->has('procurement'))
<span class="help-block">
<strong>{{ $errors->first('procurement') }}</strong>
</span>
#endif
</div>
I am reusing the form for editing purposes so I want to be able to bind the object's value for 'procurement' when I present the form in edit view. I am able to use this bind the values for text inputs;
value="{{ isset($vehicle->model) ? $vehicle->model : old('model') }}"
But this does not work for radios or selects. What should I be doing? I am NOT using the Form facade for this.
Thanks!
You can use selected and checked for what you want to do. Just add it to the end of the element, and it will select/check the element.
Something like this for input type radio:
<input id="procurement" type="radio" name="procurement" value="owned" {{ old('model') === "owned" ? 'checked' : (isset($vehicle->model) && $vehicle->model === 'owned' ? 'checked' : '') }}> Owned
<input id="procurement" type="radio" name="procurement" value="rental" {{ old('model') === "owned" ? 'checked' : (isset($vehicle->model) && $vehicle->model === 'rental' ? 'checked' : '') }}> Rental
And this for select options:
<option value="something" {{ old('model') === "something" ? 'selected' : (isset($vehicle->model) && $vehicle->model === 'owned' ? 'selected: '')}}>Something</option>
Side note: I'd recommend making sure that old('something') comes before other possible values when you're filling values in. For instance, you had:
value="{{ isset($vehicle->model) ? $vehicle->model : old('model') }}"
which would override the user's original input with database results (if any, of course) upon a failed submission. So if I was say, updating my name in a text field, and there were errors to the form, it would direct me back to the form and lose my input because the database results are before the old value. Hope that makes sense!

Laravel applying search filers

I have a page which has a search box(input text) which takes a place name as input and returns all the nearby dealers.
I also happen to have filters (checkboxes) for all the brand
<div class="col-sm-12 col-md-12">
{!! Form::checkbox('filters',$bike_oem, false,['style'=>'padding-right:5px;'] ) !!} <span style="padding-left:5px;"></span>{{ $bike_oem }}
</div>
How do I implement get the value of filter in my controller ?
<div class="col-sm-12 col-md-12">
<input style="padding-right:5px;" name="Hyundai " type="checkbox" value="Y"> <span style="padding-left:5px;"></span>Hyundai
</div>
This is how each filter appears in the page. Is the code correct to fetch the value in controller ? Please suggest
You can get the value of checkbox in this way also(in controller)
public function myFunction(Request $request){
if (isset($request['Hyundai']) && ($request['Hyundai'] == "on")) {
$value = "Y";
}
}

Resources