Search code examples
laravellaravel-8laravel-validation

Using required_without on Nested form


I have a request in the format

array:2 [▼
  "_token" => "Lqn3XPvbdhLC8iqs461xSrGYPmxmSv4PGCqH7LJQ"
  "branch" => array:16 [▼
    "customer_company_id" => "5"
    "is_main" => "true"
  ]
]

I need to validate the form in the following way:

  1. If customer_company_id is present name is not required
  2. If customer_company_id is not present name is required

My FormRequest looks like

public function rules(): array
    {
        return [
            'branch' => [
                'is_main' => [
                    'required',
                    'boolean'
                ],
                'customer_company_id' => [
                    'required_without:branch.name'
                ],
            ],
        ];
}

it throws the following error

Method Illuminate\Validation\Validator::validateRequiredWithout:branch.name does not exist

Solution

  • how about this?

    return [
        'branch.name' => 'required_without:branch.customer_company_id',
        'branch.is_main' => 'required|boolean',
        'branch.customer_company_id' => 'required_without:branch.name',