You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

Solution for Conditional Validation in Laravel Request Class

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,1 rule tells Laravel: "Only enforce this field as required when the supplier_id field has a value of 1."
  • When supplier_id is any value other than 1, ID_cost and entry_Fee will be treated as optional. You can add additional rules (like numeric or min:0) if needed, e.g., ['required_if:supplier_id,1', 'numeric', 'min:0'].

内容的提问来源于stack exchange,提问作者Nour Hambarosh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 12:49:07