簡體   English   中英

Laravel 驗證取決於另一個 model,其 ID 位於同一表單上

[英]Laravel validation depending on another model whose ID is on the same form

我有一個返回字段entity_idprice的表單。

$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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM