Laravel API请求验证中条件规则的实现——supplier_id为1时ID_cost与entry_Fee字段必填的配置方法
Hey there! Let's tackle this conditional validation in your Laravel Request class. Here's how you can set it up properly:
First, your conditional validation rules should be defined directly in the rules() method of your Request class. Laravel has a built-in required_if validation rule that perfectly fits your use case—it makes a field required only when another field matches a specific value.
Step 1: Update the rules() Method
Modify your rules to add the conditional requirement for ID_cost and entry_Fee:
public function rules() { return [ 'purchase_id' => ['required'], 'supplier_id' => ['required'], 'shipping_type' => ['required'], 'purchase_date' => ['required'], 'picture' => ['nullable'], 'ID_cost' => ['required_if:supplier_id,1'], // Required only when supplier_id equals 1 'entry_Fee' => ['required_if:supplier_id,1'], // Same conditional requirement ]; }
Step 2: Fix the validated() Method (Important!)
Right now, your validated() method is returning a hardcoded array, which bypasses Laravel's default validated data handling. This is risky because if you ever update your validation rules, you'll have to manually sync this array too. Instead, you should either:
- Remove the
validated()method entirely (Laravel's default implementation automatically returns all validated fields), or - Call the parent class's
validated()method to get properly sanitized, validated data:
public function validated($key = null, $default = null) { $validatedData = parent::validated(); // If you need to modify the data before returning, do it here (optional) // Example: $validatedData['custom_field'] = 'some_value'; return data_get($validatedData, $key, $default); }
How It Works
- The
required_if:supplier_id,1rule tells Laravel: "Only enforce this field as required when thesupplier_idfield has a value of 1." - When
supplier_idis any value other than 1,ID_costandentry_Feewill be treated as optional. You can add additional rules (likenumericormin:0) if needed, e.g.,['required_if:supplier_id,1', 'numeric', 'min:0'].
内容的提问来源于stack exchange,提问作者Nour Hambarosh

