📅  最后修改于: 2023-12-03 14:43:45.772000             🧑  作者: Mango
required_if
The required_if
rule in Laravel is used to specify that a field is required if another field has a specified value or meets a specified condition. It provides a powerful way to define conditional validation rules for form input data.
The required_if
validation rule allows you to specify two parameters:
Here's an example that demonstrates the usage of required_if
rule:
$request->validate([
'role' => 'required_if:type,admin',
'type' => 'in:admin,user',
]);
In this example, the role
field is only required if the value of the type
field is equal to admin
. If the type
field is user
, then the role
field is not required.
You can also use closures or custom conditional callbacks for more complex conditional validation. Here is an example:
$request->validate([
'role' => [
'required_if' => function ($attribute, $value, $fail) {
if ($value == 'admin' && empty(request('type'))) {
$fail('The type field is required when role is admin.');
}
},
],
]);
This allows you to define custom logic to determine whether the field is required based on various conditions.
Please find the below code snippet that demonstrates the usage and functionality of the required_if
rule using Laravel:
```php
$request->validate([
'role' => 'required_if:type,admin',
'type' => 'in:admin,user',
]);
This code shows how to use the required_if
rule to conditionally require the role
field based on the value of the type
field.