📜  laravel required_if - PHP (1)

📅  最后修改于: 2023-12-03 14:43:45.772000             🧑  作者: Mango

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

Usage

The required_if validation rule allows you to specify two parameters:

  1. The name of the other field which determines whether the current field is required.
  2. The value or condition that the other field should have for the current field to be required.

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.

Markdown

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.