0

I'm sending have an array of JSON objects that I'm POSTing to the DB with other data:

{
   "emotions":[
      {
         "id":1,
         "intensity":67,
         "new_intensity":67
      },
      {
         "id":2,
         "intensity":67,
         "new_intensity":67
      },
      {
         "id":3,
         "intensity":64,
         "new_intensity":64
      },
      {
         "id":4,
         "intensity":64,
         "new_intensity":64
      },
      {
         "id":5,
         "intensity":64,
         "new_intensity":64
      }
   ],
   "situation":"An event",
   
}

What I want to do is validate both the situation and emotions[{},{}] json array:

Controller

public function store(Request $request)
{
   $this->validate($request, [
      'situation' => 'required',
   ]); 
   $data = ['data' => $request->input('emotions')];
   $this->validate($data, [
      'data.*.id' => 'digits:2|between:1,70',
      'data.*.intensity' => 'digits:3|between:1,100',
      'data.*.new_intensity' => 'digits:3|between:1,100'
   ]);
}

Error

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

I'd like to be able to combine the two validating methods, but I have no idea how to do that as well?

Here is the answer I got my first try from

Kyle Corbin Hurst
  • 917
  • 2
  • 10
  • 26

1 Answers1

1

You can use array validators. Something like below code may help you achieve this

$validator = Validator::make($data, [
      'data.*.id' => 'digits:2|between:1,70',
      'data.*.intensity' => 'digits:3|between:1,100',
      'data.*.new_intensity' => 'digits:3|between:1,100'
   ])

You can check whether it fails and do your desired action

if($validator->fails()){
    // Do something
}
SEYED BABAK ASHRAFI
  • 4,093
  • 4
  • 22
  • 32