Laravel Validate Empty Array

The Laravel framework provides a convenient way to validate arrays using the array validation rule. You can use this rule to ensure that an array is not empty.

Example:

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

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

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

        // Array is valid
    }
}
    
  

In this example, we are using the array validation rule to ensure that the value of a request parameter named my_array is an array. Additionally, we are using a custom not_empty_array rule to ensure that the array is not empty.

You can define the not_empty_array rule by extending Laravel’s built-in Illuminate\Contracts\Validation\Rule contract. Here’s an example implementation:

    
use Illuminate\Contracts\Validation\Rule;

class NotEmptyArray implements Rule
{
    public function passes($attribute, $value)
    {
        return is_array($value) && !empty($value);
    }

    public function message()
    {
        return 'The :attribute must not be an empty array.';
    }
}
    
  

To use the NotEmptyArray rule, you can register it in your AppServiceProvider or directly in your controller. For example, in your controller:

    
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Rules\NotEmptyArray;

class ExampleController extends Controller
{
    public function validateArray(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'my_array' => ['array', new NotEmptyArray],
        ]);

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

        // Array is valid
    }
}
    
  

With this implementation, if the my_array parameter is not an array or is an empty array, validation will fail, and you can handle the error accordingly.

Leave a comment