I'm working with forms where the checkboxes are present, but the target model's fields must be in boolean type, since they are defined in my migrations as boolean. For example:
$table->boolean('is_active')->default(true); The Model's values are filled in this way:
foreach (static::getFillableFields() as $field) { $entry->$field = $request->input($field); } So I added the cast to make this field boolean:
class Entry extends Model { protected $casts = [ 'is_active' => 'boolean', ]; But now what I see: when the form's checkbox is checked and I have '1' string in the request, it works well - '1' gives 'true' when I access $entry->is_active then. But when checkbox isn't checked, it gives the 'null' value, and - I don't know why - when the model's field is set to null, then it returns null (not 'false', as I expected). Why is it so? This makes casts useless in my case. Can I change this behavior?
I'm not too inspired with idea of adding this (accessors/mutators) for every boolean field (but in fact this results in what I need):
public function setIsActiveAttribute($value) { $this->attributes['is_active'] = (bool)$value; } public function getIsActiveAttribute(bool $value): bool { return $value; }
$this->attributes['is_active'] = is_null($value) ? false : (bool)$value?groupBy()yet its actually the solution to my understanding)