Laravel Validation with checkbox - php

If use_shipping is un-checked and user did not enter the value in the shipping_note - validation should have passed but it has failed?
<input type="hidden" name="use_shipping" value="0">
<input type="checkbox" name="use_shipping" value="1" {{ old('use_shipping', $delivery->use_shipping) ? 'checked="checked"' : '' }}>
Text
<input type="text" name="shipping_note" value="">
In Laravel request class:
public function rules()
{
return [
'use_shipping' => 'boolean',
'shipping_note' => 'required_with:use_shipping',
];
}

The required_with validation states:
The field under validation must be present and not empty only if any of the other specified fields are present.
Because of your hidden input, the shipping_note field will always be present. Since the field is present even when the checkbox is unchecked, the required_with validation will always be triggered.
Most likely what you're looking for is the required_if validation, which states:
required_if:anotherfield,value,...
The field under validation must be present and not empty if the anotherfield field is equal to any value.
public function rules()
{
return [
'use_shipping' => 'boolean',
'shipping_note' => 'required_if:use_shipping,1',
];
}
This should cause shipping_note to only be required when the value of use_shipping is 1, which should only happen when the checkbox is checked.

Related

Laravel Array to Input checkbox true or false value

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.

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');

Validation Laravel of 2 fields : first is datepicker and second is select

I have many fields on my form.
2 of them have to bind together.
The first is an datepicker and the second a select field (filled in function of date chosen).
<input class="form-control pull-right" name="day_desired" id="day_desired" placeholder="Day Desired" type="text" value="{{ old('day_desired') }}">
<select id="hour_id" name="hour_id" class="form-control">
<option value="0">--- Choose hour ---</option>
<option value="10:00">10h00</option>
...
</select>
So I want to do this :
If no date chosen, these 2 fields are optionals.
If a date is chosen, the select field is required and not equal to 0 (0 is the first value of options and I use it like a label).
I had many tests with required_if, required_unless no success....
return [
'name'=>'required',
'first_name' =>'required',
...
'day_desired' =>'nullable',
'hour_id' =>'nullable'
];
Thank you very much
The required_if and required_unless checks will look for a certain condition for the value of another field. That is not what you need here.
You can use required_with:
'day_desired' =>'nullable',
'hour_id' =>'required_with:day_desired|nullable|min:1'
The reason that hour_id has to be nullable is that you don't want the min:1 check to run when the day_desired and the hour_id are empty. Still, the required_with rule will fail, even though the field is nullable, as pointed out in this post on GitHub. This behaviour was added in this release: https://github.com/laravel/framework/releases/tag/v5.4.16.

Form input not validate if input is disabled

I have a selection that is disabled is the page not editable is.
Here is my code:
<select name="status" class="form-control" id="status" #if($page->editable == 0) disabled #endif>
<option value="1" #if ($page->status == 1) selected #endif>Online</option>
<option value="0" #if ($page->status == 0) selected #endif>Concept</option>
</select>
But as the input is disabled he send no values with.
And now comes the problem.
I validate the form. Here is my code of validate the form:
$form = $request->validate([
'status' => 'required',
]);
But I get the error now that the value status is empty and required.
Do you now how to set the validation that he only is required is the form is not disabled?
I hope that you can help me.
Firstly, You should use separate function for store and update,
For store, Your validation code seems right, but you can add boolean rule
$form = $request->validate([
'status' => 'required|boolean',
]);
For update, you can use validation rule like this,
$form = $request->validate([
'status' => 'nullable|boolean',
]);
If you are using same function for store and update, you should send value for editable status and you can apply validation rules according editable status like this,
if ($request->editable) {
....
}
else {
...
}
I hope this will help

Laravel custom validation rule that works with not required empty field

I have required file field which is recorded in the database as a path. I want to make it optionally required if its field in the database is null. In the update action of my controller I have set the following validation:
$this->validate(request(),[
'drawings' => 'requiredIfEmpty:'.$product->drawings.'|file|max:'. config('fox.photoMaxSize').'|mimes:pdf',
Then in app/Providers/AppServiceProvider.php I defined requiredIfEmpty validator:
Validator::extend('requiredIfEmpty',function ($attribute,$value,$parameters,$validator){
if(is_null($parameters[0]) || empty($parameters[0])){
if (is_null($value)){
return false;
}
}
return true;
});
Validator::replacer('requiredIfEmpty', function ($message, $attribute, $rule, $parameters) {
return __('The :attr is required',['attr' => $attribute]);
});
In the view _form I use laravelcollective form helper like the following for the drawings field:
<div class="form-group {{$errors->first('drawings','has-error')}}">
#if (!is_null($product->drawings))
<img src="/imgs/pdf.png" alt="{{__('PDF File')}}" title="{{__('PDF File')}}" />
<br>
#else
<img src="/imgs/empty.png" width="64" height="64" alt="{{__('Empty')}}..." title="{{__('Empty')}}..." /> <br>
#endif
{!! Form::label('drawings', __('Drawings')) !!}
{!! Form::file('drawings',['class' => 'btn btn-info','title' =>__('PDF file')]); !!}
#php ($eleE = $errors->first('drawings'))
#include('layouts.form-ele-error')
</div>
The problem is, my custom validation rule does not invoked because the field is not required and it has null value. I need any way that allows the two scenarios:
when the drawings file field is empty and $product->drawings is not null, there's no validation occured
when the drawings file field is empty and $product->drawings is null, the validation occurred.
In other words, I need a built in validation rule like requiredIf but it does not take another form field as parameter, it just take another value and it always works even the form field value is empty and the field is not required.
You should use the extendImplicit function to run rules when their values are empty.
Validator::extendImplicit('required_if_exists', function($attribute, $value, $parameters, $validator) {
//
});
Alternatively, in a Rule class, you should implement the ImplicitRule interface instead of Rule.
use Illuminate\Contracts\Validation\ImplicitRule;
class RequiredIfExists implements ImplicitRule {
//
}
I have found a solution that does not related directly with Laravel validation. It will depend on keeping original validation for the file field and keep it not required then make validation logic in the controller's action that return errorbag message if an error is found. The solution looks like the following snippet:
public function update(Request $request, Product $product)
{
$product = Product::find(request('product'));
$this->validate(request(),[
'drawings' => 'file|max:'. config('fox.photoMaxSize').'|mimes:pdf' //Original validation
]);
if(is_null($request->drawings) && is_null($product->drawings)){
return redirect()->back()->withErrors(['drawings' => __('A drawing file must be specified')]);
} //If the field is null and the database attribute is null too an error message is returned to form's file field.
...
}
However, this solution does not answer how could we define a custom validation rule that always invoked regarding-less the field is set required or not?
Reference

Categories