Go Mommy Go Mommy - 1 year ago 140
PHP Question

Laravel Array Validation

$rules = [
'user_id' => 'required|exists:users,id',
'preparat_id' => 'required|exists:preparats,id',
'zoom' => 'required|numeric',
'comment' => '',
'type' => 'in:' . Annotation::ANN_RECTANGLE . ',' . Annotation::ANN_CIRCLE . ',' . Annotation::ANN_POLYGON . ',' . Annotation::ANN_PIN,
'point_x' => 'array|required|numeric',
'point_y' => 'array|required|numeric',
];

$this->validate($request, $rules);


point_x and point_y is an array input.

My rule is :
point_x and point_y must be exist.

How i send data :


  • point_x[0] = 123;

  • point_y[0] = 123;



TRUE





  • point_x[0] = 123;

  • point_y[0] = 123;

  • point_x[1] = 123;

  • point_y[1] = 123;

  • point_x[2] = 123;

  • point_y[2] = 123;



TRUE




point_x[0] = 123;
point_y[0] = "SO";

WRONG




point_y[0] = 123;

WRONG





  • point_x[0] = 123;

  • point_y[0] = 123;

  • point_x[1] = 123;

  • point_y[1] = "Taadaa";

  • point_x[2] = 123;

  • point_y[2] = 123;



WRONG

My Laravel version is 5.4

How should i write a rule for check like above. I tried to array parameter, but i does not work.

Answer Source

Try following rules for arrays point_x and point_y only,

$this->validate($request, [
    'point_x' => 'required',
    'point_y' => 'required',
    'point_x.*' => 'numeric',
    'point_y.*' => 'numeric',
], 
     $messages = [

     ]
);

See docs Array Input Validation

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download