伙計們,我正在嘗試驗證類別是否屬于某個用戶,我已經嘗試過,但是當我輸入一個不存在的值時出現錯誤。我嘗試了什么:
'category' => ['nullable','exists:categories,id', function ($attribute, $value, $fail) {
$category = Category::where('id', $value)->first();
if($category->vcard!= $this->vcard->phone_number)
{
$fail('The selected category is invalid.');
}
}]
因此,當我輸入有效類別時,這會起作用,但是如果我輸入了錯誤的類別,例如不存在的類別 ID 100000,則會在郵遞員上向我拋出此錯誤:

我認為這'exists:categories,id'會解決我,不存在的 ID。
作品:
{
"payment_reference": "[email protected]",
"payment_type": "PAYPAL",
"type": "D",
"value": 10,
"description": "Teste",
"category": 500
}
不作業:
{
"payment_reference": "[email protected]",
"payment_type": "PAYPAL",
"type": "D",
"value": 10,
"description": "Teste",
"category": 1000000
}
uj5u.com熱心網友回復:
解決此問題的一種簡單方法是檢查是否$category為空:
if($category && $category->vcard != $this->vcard->phone_number) {
$fail('The selected category is invalid.');
}
使用find或first與 Eloquent 一起使用時,如果模型存在null則回傳模型,如果不存在則回傳模型。
或者,您可以將保釋驗證規則用于category:
'category' => [
'bail',
'nullable',
'exists:categories,id',
function ($attribute, $value, $fail) {
$category = Category::where('id', $value)->first();
if ($category->vcard != $this->vcard->phone_number) {
$fail('The selected category is invalid.');
}
},
],
這意味著如果exists規則失敗,閉包甚至不會被執行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/367904.html
