You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Vue Inertia:如何接收复选框数据并更新至数据库?

Solution

The issue comes from two key problems:

  • Checkboxes emit the change event (not input), so your update function doesn't trigger when toggling the checkbox.
  • The checkbox's true-value and false-value are set as string literals, which may not match the data type your backend expects (e.g., integers or booleans).

Fixes:

  1. Listen for both input and change events
    Modify the parent div to trigger update on both events, covering text inputs (which use input) and checkboxes (which use change):

    <div @input="update" @change="update">
    
  2. Use correct value types for the checkbox
    If your backend expects integer values (1/0) for the paid field, bind the values as numbers using v-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-value and false-value attributes 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 12:40:17