Laravel/LiveWire项目中category_id传值为null的问题求助
Laravel LiveWire 中 category_id 始终为 null 的问题
我在开发Laravel/LiveWire项目时,遇到一个问题:product.blade.php中的category_id参数传递到store函数时始终是null。我检查了输入项、模型,也在组件中定义了category_id,没发现明显问题。
我已经执行了缓存、配置相关的Artisan清理命令,甚至创建了不同名称的新组件,但问题依旧。
dd输出结果
array:8 [▼ "title" => "تراکت" "en_title" => "tracket" "category_id" => null "description" => "nothing" "status" => 1 "img" => null "price" => "48000" "keywords" => "tracket" ]
LiveWire产品Blade代码
<div class="form-group"> <label class="form-label">دسته بندی محصول</label> <select wire:model="category_id" id="select-countries" class="form-control custom-select"> @foreach($categories as $category) <option value="{{$category->id}}">{{$category->title}}</option> @if(count($category->childrenRecursive) >0) @include('Admin.category.partials',['categories'=>$category->childrenRecursive,'level'=>1,'create'=>1]) @endif @endforeach </select> </div>
LiveWire组件代码
<?php class Index extends Component { public $title,$en_title,$category_id,$description,$status=1,$img=null,$price,$keywords; public function store(){ $keywords=serialize(explode(",",$this->keywords)); Product::create([ 'title'=>$this->title, 'en_title'=>$this->en_title, 'category_id'=>$this->category_id, 'description'=>$this->description, 'status'=>$this->status, 'price'=>$this->price, 'image'=>$this->img, 'keywords'=>$keywords, ]); $this->reset(['title','en_title','category_id','description','price']); session()->flash('add_product','محصول شما با موفقیت اضافه شد'); } public function render() { $categories=Category::with('childrenRecursive')->where('parent_id',null)->get(); $products=Product::latest()->paginate(8); return view('livewire.admin.product.index',compact('categories','products'))->extends('layouts.admin')->section('content'); } }
可能的解决方法
检查子分类的option标签
你用@include加载子分类的partial视图,要确保partial里的<option>标签正确设置了value属性,比如:<option value="{{ $category->id }}"> {{ str_repeat('— ', $level) }}{{ $category->title }} </option> @if(count($category->childrenRecursive) > 0) @include('Admin.category.partials', ['categories' => $category->childrenRecursive, 'level' => $level + 1, 'create' => 1]) @endif若partial中的option未正确设置
value,会导致选中后无法传递category_id。确认LiveWire必要资源加载
检查layouts.admin布局文件是否包含LiveWire脚本:@livewireScripts同时确保提交按钮使用
wire:click="store",而非普通表单提交。验证组件命名空间
确认Index组件的命名空间正确,比如namespace App\Http\Livewire\Admin\Product;,否则LiveWire无法正确识别组件,导致数据绑定失效。实时调试绑定值
在Blade中添加{{ $category_id }},查看选择下拉框时该值是否变化。若未变化,检查wire:model拼写是否正确,是否嵌套在冲突的JS或表单代码中。再次检查模型$fillable
确认Product模型的$fillable数组包含category_id:protected $fillable = [ 'title', 'en_title', 'category_id', 'description', 'status', 'price', 'image', 'keywords' ];
内容的提问来源于stack exchange,提问作者foad
相关产品推荐
相关产品推荐

