Laravel Validate Multidimensional Array

To validate a multidimensional array in Laravel, you can make use of Laravel’s validation rules and custom validation functions.

Let’s say you have a form with multiple input fields in an array structure like this:

    
      <form action="/your-route" method="POST">
        <input type="text" name="data[0][name]" />
        <input type="text" name="data[0][email]" />
        <input type="text" name="data[1][name]" />
        <input type="text" name="data[1][email]" />
        <!-- ... more input fields ... -->
      </form>
    
  

In your Laravel controller or request class, you can define the validation rules for the multidimensional array. For example:

    
      class YourController extends Controller
      {
          public function store(Request $request)
          {
              $rules = [
                  'data.*.name' => 'required|string|max:255',
                  'data.*.email' => 'required|email',
              ];

              $validatedData = $request->validate($rules);

              // Rest of your code
          }
      }
    
  

In the above example, we are specifying the validation rules for the ‘name’ and ’email’ fields in the multidimensional ‘data’ array. The ‘*’ wildcard tells Laravel to apply the rule to all elements of the array.

You can also create custom validation functions if you need to perform more complex validation on the multidimensional array. For example:

    
      Validator::extend('custom_rule', function ($attribute, $value, $parameters, $validator) {
          // Perform your custom validation logic here
      });

      $rules = [
          'data.*.name' => 'required|string|max:255',
          'data.*.email' => 'required|email',
          'data.*.custom_field' => 'custom_rule'
      ];
    
  

In the above example, we defined a custom validation rule ‘custom_rule’ for the ‘custom_field’ in the ‘data’ array. You can define the custom validation logic in the callback function.

Same cateogry post

Leave a comment