Sunday, July 24, 2022

[FIXED] how to validate json data in laravel

Issue

Here is the json data I send through postman for 'specification' field:

{
"specification": [
    {
      "type": [
          {
              "type": "Smartphone , Phablet , Notch Phone , Camera Phone , Selfie Phone",
              "shape": "Bar"
          }
      ],
      "basic": [
          {
              "os": "Smartphone , Phablet , Notch Phone , Camera Phone , Selfie Phone",
              "Sim": "Bar"
          }
      ]
    }
  ]
}

Then in controller the validation rule is:

'specification' => 'required|json'

The error message: "The specification must be a valid JSON string."

how can I send and check valid json in laravel controller?


Solution

From documentation:

json

The field under validation must be a valid JSON string.

Your data has been parsed from JSON by Laravel itself, and specification is an array already, not a JSON string. You can check that by changing your rule to required|array and you'll see that it passes.



Answered By - Styx
Answer Checked By - Gilberto Lyons (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.