Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel "Required" Validation Causes Validation To Fail

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    // START: Validate request
    $validator =  Validator::make($request->all(), [
        'results.*.status.*.name' => 'required|max:255|nullable',
        'results.*.error.*.name' => 'required|nullable',
        'results.*.messageId' => 'required|nullable',
        'results.*.doneAt' => 'required|date|nullable',
        'results.*.smsCount' => 'required|numeric|nullable',
        'results.*.sentAt' => 'required|nullable',
        'results.*.callbackData' => 'required|nullable',
    ]); // 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"
    }
  ]
}

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading