2 回答

TA貢獻(xiàn)1799條經(jīng)驗 獲得超6個贊
有趣的是,該 @error 指令沒有通過輸入名稱以編程方式綁定到任何輸入字段。它僅通過接近度與輸入字段在空間上相關(guān),并且可以放置在頁面上的任何位置。
@error此外,只要將相同的字符串傳遞給withErrors()控制器中的調(diào)用,您就可以方便地使用指令中的任何字符串。
因此,解決在多個輸入中定位適當(dāng)輸入的問題變得像使用任何唯一字符串(不一定是目標(biāo)輸入名稱)作為withErrors()方法調(diào)用中的鍵并通過將相同的字符串傳遞給@error指令來檢索錯誤消息一樣簡單。就我而言,我選擇使用帳戶 ID 作為唯一字符串。
在AccountController.php:
public function update(Request $request, Account $account)
{
if($request->input('credit') < 0)
{
return back()->withErrors([$account->id=>'enter a positive amount']);
}
// ... other logic
}
在 html 刀片模板中:
@forelse($accounts as $account)
<form method="POST" action="{{ route('account.update', $account->id) }}">
@csrf
<div>
<input type="number" name="credit" class="@error($account->id) is-invalid @enderror" required>
<input type="submit" class="btn" value="ok">
@error($account->id)
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</form>
@empty
@endforelse
注意:在任何指令中使用不存在的鍵@error會破壞其他 @error 指令的代碼,并且不會導(dǎo)致顯示錯誤消息。

TA貢獻(xiàn)1799條經(jīng)驗 獲得超8個贊
解決方案將執(zhí)行以下操作:
使用提交按鈕的值將值/發(fā)布的表單存儲在變量中
放棄錯誤指令并使用舊版本
將舊版本與變量結(jié)合起來檢查你是否有正確的形式
你會得到這樣的東西:
@if ($errors->has('email') && $submitted_form_identifier === $form_identifier)
<span>{{ $errors->first('email') }}</span>
@endif
- 2 回答
- 0 關(guān)注
- 310 瀏覽
添加回答
舉報