Home > Back-end >  Laravel "Required" Validation Causes Validation To Fail
Laravel "Required" Validation Causes Validation To Fail

Time:11-28

I'm trying to validate data gathered from a json file. If I don't include the "required" validation, the validation passes, but when I add it back in it fails for some reason. I don't understand how it would be failing if all fields it's checking against aren't null.

Anything obvious that I'm missing?

Controller:

    // START: Validate request
    $validator =  Validator::make($request->all(), [
        'results.*.status.*.name' => 'required|max:255',
        'results.*.error.*.name' => 'required',
        'results.*.messageId' => 'required',
        'results.*.doneAt' => 'required|date',
        'results.*.smsCount' => 'required|numeric',
        'results.*.sentAt' => 'required',
        'results.*.callbackData' => 'required',
    ]); // The "required" is causing the validation to fail

    if ($validator->fails()) {
        dd('fail');
    } else {
        dd('pass');
    }
    // END: Validate request

Json data:

{
 "results": [
  {
   "bulkId": "BULK-ID-123-xyz",
   "price": {
    "pricePerMessage": 0.0185,
    "currency": "GBP"
    },
    "status": {
     "id": 5,
     "groupId": 3,
    "groupName": "DELIVERED",
      "name": "DELIVERED_TO_HANDSET",
      "description": "Message delivered to handset"
    },
    "error": {
      "id": 0,
      "name": "NO_ERROR",
      "description": "No Error",
      "groupId": 0,
      "groupName": "OK",
      "permanent": false
    },
    "messageId": "MESSAGE_UUID",
    "doneAt": "2022-11-21T17:11:16.661 0000",
    "smsCount": 1,
    "sentAt": "2022-11-21T17:11:12.129 0000",
    "callbackData": "CAMPAIGN_ID",
     "to": "447572554668"
    }
  ]
}

CodePudding user response:

You simply just have to replace this:

'results.*.status.*.name' => 'required|max:255|nullable',
'results.*.error.*.name' => 'required|nullable',

With this:

'results.*.status.*' => 'required|max:255|nullable',
'results.*.error.*' => 'required|nullable',

You are getting error because of there is no name key in status properties and you want them to be required.

  • Related