Laravel - Is there any better approach to check the checkbox with the user previous input value in blade? - laravel

I have a checkbox
<input type="checkbox" name="example">
The user submits the form and return back due to failed validation so I want to show the previous state of the checkbox
<input
type="checkbox"
name="example"
{!! old('example') ? 'value="1" checked' : 'value="0"' !!}>
First question here is that, what to do with validation now? if it was 0 or 1 I would add boolean validation but now the first time it is on and after that it is 0 or 1.
Someone may say if you use that {!! old('example') ? 'value="1" checked' : 'value="0"' !!} initially, its value won't be on anymore.
So my first question changes to this: Initially the value of old('example') is null so the checkbox doesn't have checked attribute and the value of checkbox would be 0. Now when the user submits the form the old('example') has value (IT IS NOT NULL) and so this time the the checkbox has checked attribute and its value is 1 while it mustn't.
========
Another issue I encounter with is that, if old('example') has true value (which means the user had checked the checkbox), I should put something to check the checkbox. But it is not finished yet. I want to check the value of example that is in database so if the old('example') has false value(which means the user hadn't checked the checkbox) I want to check the value of example, if its value is 1 to check the checkbox and set the value of checkbox to 1 else 0. So what comes to my mind is this:
<input
type="checkbox"
name="example"
value="{!! old('example', isset($collection) ? $collection->example : null) == '1' : '1' : '0' !!}">
Now the problem is that old('example') would be on or NOTHING. And the value of $collection->example would be 1 or 0 or null. So if I compare it with '1' it won't be true even if the old('example') is true and similarly if I compare it with on, it won't be true even if the value of $collection->example is true. So let's do this:
#if(old('example') == 'on' || (isset($collection) && $collection->example))
<input type="checkbox" name="example" value="on" checked="checked">
#else
<input type="checkbox" name="example">
#endif
by this code above the issue is fixed. But is there any other better approach?
So my question is what to do with the validation in the back-end and of course what to do with check-boxes in front-end in an better approach without getting involved in jQuery and such a like?

I think it will solve your problem give it a try.
Blade file:
<input type="checkbox" name="example" value="{{ old('example') ?? '1' }}"
{{ old('example') == '1' ? 'checked' : null }} required>
The required will force the user to check the checkbox on the frontend, and on the backend, you can use the required validation because we can't trust the frontend validation.
Controller:
public function store(Request $request)
{
$request->validate([
'example' => 'required',
]);
}

Related

Checkboxes in Laravel

I'm learing laravel and have some checkboxes on my form. However by default they have the value of on and off -> null or not passed.
But in my tables are using a boolean of 0 and 1. I've covered for this in my controller which takes the on or off values and puts them to 0 or 1 .
HotelFacility::create([
'hotel_id' => $hotel->id,
'fitness_centre' => $request->has('fitness_centre') ? 1 : 0,
'bar' => $request->has('bar') ? 1 : 0,
]);
But how do I now cover for this in my blade template as it's now reading back the opposite?
<input type="checkbox" name="fitness_centre" value="{{ $hotel[0]->hotelFacilites->fitness_centre ? 'on' : 'off' }}">
Fitness Centre
</label>
Please try this because if you want to check the checkbox as per database value so you need to put checked not value.
<input type="checkbox" name="fitness_centre" {{ $hotel[0]->hotelFacilites->fitness_centre ? ' checked ':''}}>

Laravel can't uncheck checkbox using old with default value set

I have a very simple checkbox in my application form
<input type="checkbox" name="active" {{ ( empty(old('active')) ? '' : ' checked' ) }}>
My requirements are:
the checkbox should be checked by default when the user arrives on the site for the first time
the checkbox should keep its value after the form validation fails
To me, it seems impossible to achieve this simply by using old as it will either
(2) remember the value after validation fails but it will not be checked by default at the beginning
(1) be checked by default, e.g. old('active', true) but then it will not be possible to uncheck it (i.e. unchecked box will be checked after validation fails because the default value is set in old).
What is the standard way of dealing with this? Or is there no way around using another field to check if the form was submitted?
<input type="checkbox" name="active" {{ ( empty(old('active')) && !empty(old('submit')) ? '' : ' checked' ) }}>
<input type="hidden" name="submit" value="submit">
Thank you
This maybe dirty but you can append empty string if the $request->active is null.
The code is something like this $request->active ?? '';.
You can pass the default value into old helper.
Try this:
<input type="checkbox" name="active" {{ old('active', true) ? 'checked' : '' }}>

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

Single Checkbox Form Laravel 5.5

I'm working on a webpage where users can click a checkbox; any user can click the checkbox, and the result will be the same when viewed by all users. So, if User A checks the box, User B will see it as checked. If User B then unchecks it, User A will see it as unchecked.
I can get the checkbox to display the value from the database, but I can't seem to get the value to change and update in the database when a user clicks on the checkbox.
My blade layout looks like this:
<form method="POST" action="{{ action('QuestionController#answered', $question->id) }}" role="form">
{{ csrf_field() }}
<input type="checkbox" id="answered" name="answered" value="0" #if($question->answered == 1) checked #endif> Answered
</form>
The function in my controller looks like this:
public function answered(Request $request, $id)
{
$request->request->add(['answered_userid' => $this->userId]);
$this->validate($request, [
'answered' => 'required',
'answered_userid' => 'required'
]);
Question::find($id)->update($request->all());
}
}
And, in my routes file, I have this:
Route::post('questions/answered', ['as' => 'questions.answered', 'uses' => 'QuestionController#answered']);
EDIT: I've updated it to include the name, but I'm still running into the same problem.
You have to set a name in the input. The request will use the name of the input as the parameter:
<input type="checkbox" name="answered" id="answered" value="0" #if($question->answered == 1) checked #endif>
Set the name and its value
<input type="checkbox" name='answered' {{$question->answred ==1 ? Value="1" checked : value="0"}}>

What is the best practice to show old value when editing a form in Laravel? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed last year.
The community reviewed whether to reopen this question last year and left it closed:
Original close reason(s) were not resolved
Improve this question
I am writing the logic for an edit form and have some complications when displaying data in the inputs.
When I initially show the form, I show the records values like:
value="{{$dog->title}}"
Then when the form does not pass the validation I need to show the old input, so that user does not loose what he has already input. So I need to have a way to display old data like:
value="{{old('title')}}"
Because I need to input old data in case it exists, I ended up with this code:
value="{{$dog->title or old('title')}}"
And in controller I check if Request has old input, I assign the $dog var a null value.
I wanted to ask if that is considered an OK practice or is there a better and 'correct' way to do it?
Function old have default parameter if no old data found in session.
function old($key = null, $default = null)
You can replace expression in template with
value="{{old('title', $dog->title)}}"
I know this has already been answered but I thought I would leave a little snippet here for others in the future.
Setting old value on input as #ikurcubic posted can be used the same way on radio button or select:
<input type="text" name="name" value="{{ old('name', $DB->default-value) }}" />
Select option:
<option value="Jeff" {{ old('name', $DB->default-value) == 'Jeff' ? 'selected' : '' }}>Jeff</option>
Radio Button:
<input type="radio" name="gender" value="M" {{ old('name', $DB->default-value)== "M" ? 'checked' : '' }} />
Another way of doing it; write a small if statement to determine which value should be evaluated:
#php
if(old('name') !== null){
$option = old('name');
}
else{ $option = $database->value; }
#endphp
<select name="name">
<option value="Bob" {{ $option == 'Bob' ? 'selected' : '' }}>Bob</option>
<option value="Jeff" {{ $option == 'Jeff' ? 'selected' : '' }}>Jeff</option>
</select>
<input type="radio" name="gender" value="M" {{ $option == "M" ? 'checked' : '' }} />
<input type="radio" name="gender" value="F" {{ $option == "F" ? 'checked' : '' }} />
Setting old value of input with an array name e.g name="name[]":
<input type="text" name="name[]" value="{{ old('name.0) }}" />
This will give you the old value of the input with an index of 0.
I have tested this and it works.
Another way to do that is get the data from the dog class, like this:
value="{{old('title') ?? $dog->title }}"
Why? Because old() is for validation; when you fail validation, the input will remain available in the field. In the case where validation hasn't fired yet, value will be filled with $dog->title.
I solved that issue in my application
if you want to get old previous inserted value in input you should try this one
I did like this.
function SaveData(Request $request)
{
$sValidationRules = [
'firstname' => 'required',
'lastname' => 'required',
'email' => 'required',
'phone' => 'required',
];
$validator = Validator::make($request->all(), $sValidationRules);
if ($validator->fails()) // on validator found any error
{
// pass validator object in withErrors method & also withInput it should be null by default
return redirect('Your Route Hare')->withErrors($validator)->withInput();
}
Employee::create($request->all());
return redirect(' your route hare ');
}
& after then get old data in input field value like this using {{ Request::old('firstname') }}
Happy Coding. :)
<input type="text" name="firstname" id="firstname" value="{{ Request::old('firstname') }}" class="form-control" placeholder="First Name">
Old Data: input type text | phone | number | ...
<input type="text" name="my_text" value="{{old('my_text')}}">
Old Data: input type checkbox | radio
<input type="checkbox" {{ old('my_checkbox') == 'on' ? 'checked' : '' }} name="my_checkbox">
There is nothing wrong with the way you are doing things as Laravel gives multiple ways to handle the situation you're describing.
What I would suggest is using the Laravel Collective Form and HTML packages to build your form. This package will automatically handle binding old request values to your form if validation fails
https://laravelcollective.com/docs/5.2/html

Resources