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

Laravel Livewire表单中Auth::user()->id显示正常但提交返回null如何解决

问题原因&解决办法

  • 核心原因是你没有将下拉选择器和Livewire的公共属性做双向绑定,就算option的value值渲染正常,Livewire也无法接收前端选择的内容,所以提交时拿到的值是null。
  • 你将当前登录用户ID放在前端表单传输的方案存在安全隐患,很容易被恶意篡改提交非自身的ID,更稳妥的方案是直接在后端逻辑中读取Auth数据,不需要经过前端表单传递,直接修改你的Livewire存储逻辑即可:
$this->validate([
    'customer_name'=>'required|string',
    'phone_number'=>'required|string'
]);

StokItem::updateOrCreate([
    // 直接在后端取登录用户ID,不需要走前端传值
    'customer_code'=> Auth::user()->id,
    'customer_name'=>$this->customer_name,
    'phone_number'=>$this->phone_number
]);
  • 如果你确实需要通过前端下拉选择的方式传递该值,按以下步骤排查修改:
  1. 给select标签添加Livewire双向绑定属性,假设你要绑定到customer_code字段:
<select wire:model="customer_code">
    <option value="{{ Auth::user()->id }}" data-keterangan="">{{ Auth::user()->id }}</option>
    <!-- 其他下拉选项 -->
</select>
  1. 确认你的Livewire组件类中已经声明了对应的公共属性,缺少声明的话Livewire无法正常存储前端传过来的值:
// Livewire组件类开头要定义对应公共属性
public $customer_code;
public $customer_name;
public $phone_number;
  1. 如果该选项为固定默认值、不需要用户修改,直接在组件的mount方法中给属性赋初始值即可,不需要写在前端option里:
public function mount()
{
    $this->customer_code = Auth::user()->id;
}

内容的提问来源于stack exchange,提问作者Preman Terminal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 19:15:03