Livewire绑定模型单选按钮错误
Livewire绑定模型单选按钮错误
我正在尝试使用Livewire构建一个投票系统,但是遇到了一些错误\n这是我的Blade模板:\n
@foreach ($questions as $index => $question){{ $question->title }}
@foreach ($answers as $key => $answer) @endforeach @error('question') {{$message}} @enderror @endforeach
\n我的Livewire类:\n
public $question = []; public function render() { $category = PollCategory::findOrFail($this->category->id); $subCategories = PollSubCategory::where('poll_category_id', $category->id)->get(); $answers = PollAnswer::all(); return view('livewire.polls', compact('category', 'subCategories', 'answers')); }
\n错误信息如下:\n
\n在组件[polls]上找不到属性[$question41]\n
\n请帮忙解决一下,谢谢!
问题的出现原因:在Livewire绑定模型的单选按钮中,使用了错误的语法,导致出现错误。
解决方法:将代码修改为正确的语法,即使用正确的变量名进行绑定。
具体修改方法如下:
原因是`$question->id`表示的是`$question`数组中的第41个元素,而`question.{{ $question->id }}`表示的是`question`数组中的第41个元素的值。
因此,当使用`$question.{{ $question->id }}`进行绑定时,会出现错误提示`Property [$question41] not found on component`。
为了验证所有的问题是否都被填写,可以使用以下代码:
$this->validate([ 'question.*' => 'required', ]);
需要注意的是,`*`符号用于检查数组中的值,而不是数组本身。
如果想要验证所有的问题是否都被填写,可以使用以下代码:
foreach($question as $key => $q) { $this->validate([ 'question.'.$key => ['required'] ]); }
由于问题数组是以`$question->id`的形式存在的,而不是以`$key`形式存在的,因此需要使用`foreach`循环来遍历问题数组。
这样就可以确保所有的问题都被要求填写了。