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

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.