How To Validate The Length Of An Array In Laravel 10

Here is an example of how to validate the length of an array in Laravel 10:

PHP

<?php

namespace App\Http\Controllers;

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

class ArrayLengthValidationController extends Controller
{
    public function index(Request $request)
    {
        $data = $request->all();

        $validator = Validator::make($data, [
            'array' => 'required|array|min:3',
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors(), 422);
        }

        return response()->json(['success' => true]);
    }
}

In this example, we are validating the array field, which is an array of integers. The required rule ensures that the field is not empty, the array rule ensures that the field is an array, and the min:3 rule ensures that the array has at least 3 elements.

If the validation fails, the controller will return a JSON response with the error messages. Otherwise, the controller will return a JSON response with a success message.

Here is an explanation of the code:

  • The Validator::make() method creates a new validator instance.
  • The required rule ensures that the field is not empty.
  • The array rule ensures that the field is an array.
  • The min:3 rule ensures that the array has at least 3 elements.
  • The fails() method returns true if the validation fails.
  • The errors() method returns an array of error messages.
  • The response()->json() method returns a JSON response.

For more like this click here

Leave a Reply