Passing a boolean value from checkbox in Laravel form
If I'm understanding the problem correctly, you can cast the attribute as a boolean in the model.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $casts = [
'is_featured' => 'boolean',
'is_place' => 'boolean',
];
}
Then in your form you'll want to check that value to determine if the box is checked.
<input type="checkbox" name="is_featured" class="switch-input" value="1" {{ old('is_featured') ? 'checked="checked"' : '' }}/>
In your controller, you'll want to just check if the input is submitted. An unchecked input won't be sumitted at all.
$post->is_featured = $request->has('is_featured');
How to pass a boolean value in Laravel from a form to the Database?
Define an eloquent mutator like this in your model (\App\MyModelName.php
):
public function setXXXAttribute($value)
{
$this->attributes['xxx'] = ($value=='on');
}
where "XXX" is the tame of the database column.
The attribute xxx will be set to true
in case the value of the checkbox is 'on'
Error retrieving a checked Checkbox in Laravel as a boolean
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;
Checkbox in Laravel
Set the default value for your Checkbox to 0:
<input type="checkbox" name="is_active" value="0">
Next, handle this value in the back end:
$isActive = $request->input('is_active', 1);
This will result in 0
if it is checked, or 1
(the 2nd argument acts as a fallback) if you don't check it.
Lastly, assign it properly:
routes/web.php
:
<?php
use Illuminate\Http\Request;
Route::post('/is_active/save', function (Request $request) {
$user = auth()->user();
$user->is_active = $request->input('is_active', 1);
$user->save();
return redirect('people');
})->middleware(['auth']);
With this code, if you don't check the checkbox, the user's is_active
value will be set to 1
. If you do check it, the value will be set to 0
.
How to save a boolean value in Laravel 6?
You can check with the has method, if the value has been submitted and therefore you can insert true or false.
You can read it up here in the documenation: https://laravel.com/docs/6.x/requests#retrieving-input
So it has to be something like $request->has('wifi')
. The has method will return true, if the value is present in the request. If this value is true, you can assign true to the field, otherwise false. This would be my approach.
If you need an example, you can look at this question Passing a boolean value from checkbox in Laravel 5.8 form
not getting checkbox element value from form
So I got this working in the end. Using help from the comments:
public function saveSettings(Request $request) {
$siteName = $request->input('siteName');
$showFooter = $request->has('showFooter');
ConfigHelper::setValue('site_name', $siteName);
ConfigHelper::setValue('show_footer_message', $showFooter);
return redirect()->route('admin.settings')->with('result', 'Settings saved.');
}
For some reason, using $request->input('showFooter')
wasn't working properly. $request->get('showFooter')
brings a result when true, so adding the ternary makes it work every time.
What's the best way / best practice to handle boolean in a Laravel 8 Request class?
Since you want to touch the request before the validation, you could make use of this method: prepareForValidation()
:
Prepare Input For Validation
If you need to prepare or sanitize any data from the request before
you apply your validation rules, you may use the prepareForValidation
method:use Illuminate\Support\Str;
/**
* Prepare the data for validation.
*
* @return void
*/
protected function prepareForValidation()
{
$this->merge([
'slug' => Str::slug($this->slug),
]);
}
So in your case you can do:
public function prepareForValidation()
{
$this->merge([
'is_active' => $this->request->has('is_active')),
]);
}
How to pass Checkbox value 0 if not checked and 1 if checked using array laravel
checkboxes are only posted when they are checked, so in controller you can use this fragment
public function updateMon(Request $request) {
$request->validate([
'account' => 'required|array',
'account.*' => 'integer'
]);
$myVar = isset($request->account[0]) ? 1 : 0;
}
laravel read a checkbox value in a controller
Please have a look on the [parameter list of the Form::checkbox()
method][1].
The second parameter is your checkbox value. You manually set it to an empty string. Set it to null
in order to keep the browsers default values (laravel default is 1). The third parameter is a boolean. Set it to true to check the box and false to uncheck it.
The fourth parameter is your options array where you can specify your id. So the correct method call should be:
{{Form::checkbox('remember_me', null, false, array('id'=>'remember_id'))}}
Update:
Checkboxes that are not checked, will not be included in your POST data. So the only reliable way to verify that a checkbox has been checked is to check if it is set. That can be done using isset()
with regular PHP functions, or if laravel is being used, by using Input::has()
which returns a boolean dependent on whether your input data contains a given key.
Related Topics
PHP - Override Existing Function
Working with Japanese Filenames in PHP 5.3 and Windows Vista
How to Remove a Password from a PDF File Using PHP
Laravel Expected Response Code 250 But Got Code "530"
How to Display a PHP Variable into HTML
Laravel 5 Isdirty() Always Returns False
How to Convert a Single Array into a Multidimensional Array in PHP
Display Zend_Form_Element_Radio on One Line
PHP Undefined Variable in a Closure
Destination Path for Move_Uploaded_File in PHP
Nl2Br() Equivalent in JavaScript
Laravel Store Array in Session
Sort Array by Date in Descending Order by Date in PHP
Pdo Mssql Server - Driver Not Found