Laravel Vue Inertia:如何接收复选框数据并更新至数据库?
The issue comes from two key problems:
- Checkboxes emit the
changeevent (notinput), so yourupdatefunction doesn't trigger when toggling the checkbox. - The checkbox's
true-valueandfalse-valueare set as string literals, which may not match the data type your backend expects (e.g., integers or booleans).
Fixes:
Listen for both
inputandchangeevents
Modify the parent div to triggerupdateon both events, covering text inputs (which useinput) and checkboxes (which usechange):<div @input="update" @change="update">Use correct value types for the checkbox
If your backend expects integer values (1/0) for thepaidfield, bind the values as numbers usingv-bind(the colon:shorthand):<input v-model="form.paid" type="checkbox" :true-value="1" :false-value="0" />If your backend expects boolean values (true/false), omit the
true-valueandfalse-valueattributes entirely—checkboxes default to boolean v-model values:<input v-model="form.paid" type="checkbox" />
Corrected Code (for integer values):
<template> <form> <div> <div @input="update" @change="update"> <input v-model="form.month" type="text" /> <input v-model="form.day_deposited" type="text" /> <input v-model="form.description" type="text" /> <input v-model="form.amount" type="text" /> <input v-model="form.paid" type="checkbox" :true-value="1" :false-value="0" /> <Link :href="`/income/${props.income.id}`" method="DELETE" as="button" preserve-scroll>Delete</Link> </div> </div> </form> </template> <script setup> import { useForm } from '@inertiajs/vue3' import { Link } from '@inertiajs/vue3' const props = defineProps({ income: Object }) const form = useForm({ id: props.income.id, month: props.income.month, day_deposited: props.income.day_deposited, description: props.income.description, amount: props.income.amount, paid: props.income.paid, }) const update = () => form.put(`/income/${props.income.id}`, {preserveScroll:true}) </script>
Alternative: Use a deep watcher
For a more robust approach, replace event listeners with a deep watcher on the form object. This triggers updates whenever any field changes:
import { watch } from 'vue' watch(form, () => { update() }, { deep: true })
内容的提问来源于stack exchange,提问作者Marianne Hartigan

