PASSWORD RESET

Your destination for complete Tech news

How to check if a value is an array in laravel validation?

1.24K 0
< 1 min read

To check if a value is an array in Laravel validation, you can use the array validation rule. Here’s an example of how to check if a value is an array in Laravel validation:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

public function validateArray(Request $request)
{
    $validator = Validator::make($request->all(), [
        'my_array' => 'required|array',
    ]);

    if ($validator->fails()) {
        // Handle validation error
        // ...
    }

    // If validation passes, continue with the application logic
    // ...
}

In this example, we’re using the array validation rule to check if the my_array field is an array. If the validation fails, we handle the validation error. If the validation passes, we can continue with the application logic.

Note that the array validation rule only checks if the value is an array. If you need to check if the array has specific keys or values, you can use the array:keys or array:values validation rules. For example:

$validator = Validator::make($request->all(), [
    'my_array' => 'required|array',
    'my_array.*.id' => 'required|integer',
    'my_array.*.name' => 'required|string',
]);

In this example, we’re using the array:* wildcard syntax to validate that each element of the my_array field is an object with id and name keys, and that the id key is an integer and the name key is a string.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.