[英]Laravel validation depending on another model whose ID is on the same form
我有一個返回字段entity_id
和price
的表單。
$validated = $request->validate([
'entity_id' => ['required', 'integer'],
'price' => ['required', 'numeric', 'min:1'],
]);
price
字段應該有一個max
規則,但該值來自具有max_price
字段的所選Entity
。 然后該值應設置為max
。 我怎樣才能做到這一點?
您可以使用自定義驗證來做到這一點。
自定義驗證之一是使用閉包
$validated = $request->validate([
'entity_id' => ['required', 'integer'],
'price' => [
'required',
'numeric',
'min:1',
function ($attribute, $value, $fail) {
$max = Entity::where('id',$this->entity_id)->value('max_price');
//$max will be the desired value OR NULL
if (isset($max) && $max < $value) {
$fail('The '.$attribute.' is higher than the allowed max '.$max.'.');
}
}
],
]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.