0
votes

How to validate with custom request, my request with an array key

$request = [
  'link_inc_characteristic_id' => $inc_char_id[$i],
  'value' => $value[$i],
  'created_by' => $created_by,
  'last_updated_by' => $last_updated_by,
];

$this->validate($request, [
   'value['.$i.']' => 'max:30'
]);

$linkIncCharacteristicValue = LinkIncCharacteristicValue::create($request);
return Response::json($linkIncCharacteristicValue);

[EDIT] [CODE UPDATED] display error:

Argument 1 passed to App\Http\Controllers\Controller::validate() must be an instance of Illuminate\Http\Request, array given,

3
What errors are you getting?kalatabe
Validation does not work and no error..... input value automatic cut on database field length, no error from validation..Khoerodin
I just renewed code.. and getting errorKhoerodin
I think, you store not array to $request['value'] = $value[$i] but you trying validate 'value['.$i.']' => 'max:30', if you need validate array you must type 'value.*' => 'max:30'esperant
this my submitted data on console, with ajax ; value[18] value[19] value[20] value[5] asasasaasshgafshgafshgafshgafsfafsasasasa value[7] value[8] value[9]Khoerodin

3 Answers

2
votes

The Controller::validate() is not a generic validation method, it validates requests. For this use case, simply use the validator directly:

Validator::make($data, ['value' => 'max:30']);
1
votes

The error message is telling you what’s wrong:

Argument 1 passed to App\Http\Controllers\Controller::validate() must be an instance of Illuminate\Http\Request, array given

So pass the Request instance to the validate() method:

public function store(Request $request)
{
    $this->validate($request, [
        'value.*' => 'max:30',
    ]);
}

Check out the following resources:

0
votes

Its because I am putting the validation inside loop and not use * character to validate an array

...
for ($i=0; $i < $count ; $i++) {
   ...
   $this->validate($request, [
      'value['.$i.']' => 'max:30'
   ]);
   ...
   // save etc
}

right code, put validation before loop, and use * character for array validation :

$this->validate($request, [
      'value.*' => 'max:30'
]);
...
for ($i=0; $i < $count ; $i++) {
   // save etc
}