Laravel FormRequest handling checkbox

Updated: 7th March 2024
Tags: laravel

Handling checkbox is a bit strange/meh. So here the easiest way to handle it.

The way described here will return checkbox true if value is in "1",1,true,"true","on","yes". Otherwise you will get false.

<?php
public function rules(): array
{
    return [
        'my_checkbox' => 'required|boolean',
    ];
}

 protected function prepareForValidation()
{
    $this->merge([
        'my_checkbox' => $this->boolean('my_checkbox'),
    ]);
}

If you use very ancient laravel here info what request()->boolean() does

<?php
/**
* Retrieve input as a boolean value.
*
* Returns true when value is "1", "true", "on", and "yes". Otherwise, returns false.
*
* @param  string|null  $key
* @param  bool  $default
* @return bool
*/
public function boolean($key = null, $default = false)
{
return filter_var($this->input($key, $default), FILTER_VALIDATE_BOOLEAN);
}

So you can copy func to helpers and use helper func if needed.