I recently updated my app from laravel 5.4 to 5.7. After updating, I noticed I was getting the following error when submitting a form with an unchecked checkbox:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'mature_enabled' cannot be null
In other words, instead of returning 0 ,
Auth::user()->update([
'mature_enabled' => $request->get('mature_enabled'),
returns null on an empty checkbox. But a checked checkbox will return 1 .
This is what the field looks like in blade:
<div class="{{ $errors->has('mature_enabled') ? ' has-error' : '' }} settingsCheckbox">
<label for="mature_enabled">Show mature content. Adults Only (18+).</label>
<input type="checkbox" name="mature_enabled" value="1"
@if (Auth::user()->mature_enabled == 1)
checked="checked"
@endif
>
</div>
Why is this happening? I haven't changed anything at all since updating Laravel so I can only imagine this is a laravel issue.
Why is this happening?
Because Request::get
's signature is get($key, $default = null)
, so when the checkbox isn't checked it won't be sent at all and get('mature_enabled')
will return null
.
I haven't changed anything at all since updating Laravel so I can only imagine this is a laravel issue.
Actually, no, Laravel's Request::get()
just calls Symfony's one, and it's not recommended to use it:
* This method belongs to Symfony HttpFoundation and is not usually needed when using Laravel.
*
* Instead, you may use the "input" method.
So, you can fix your code this way:
$request->input('mature_enabled', false)
Or, if don't use validation and you'd want to ensure it's bool:
!!$request->input('mature_enabled')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.