Format validation error message as nested associative array











up vote
0
down vote

favorite












I have a Json object of data as shown below



{
"name": "something",
"location": {
"city": "some where",
"country": "some where",

}
}


Rule used to validate Request is



[
'name' => 'required',
'location.city' => 'required',
'location.country' => 'required'
]


Which returns error message like



{
"name": [
"The name field is required."
],
"location.city": [
"The location.city field is required."
],
"location.county": [
"The location.country field is required."
]
}


How can I format error message as a nested array like the Request.



{
"name": [
"The name field is required."
],
"location": {
"city": [
"The city field is required"
],
"country": [
"The country field is required"
]
}
}


Any default methods available ?
I am using IlluminateFoundationHttpFormRequest










share|improve this question




























    up vote
    0
    down vote

    favorite












    I have a Json object of data as shown below



    {
    "name": "something",
    "location": {
    "city": "some where",
    "country": "some where",

    }
    }


    Rule used to validate Request is



    [
    'name' => 'required',
    'location.city' => 'required',
    'location.country' => 'required'
    ]


    Which returns error message like



    {
    "name": [
    "The name field is required."
    ],
    "location.city": [
    "The location.city field is required."
    ],
    "location.county": [
    "The location.country field is required."
    ]
    }


    How can I format error message as a nested array like the Request.



    {
    "name": [
    "The name field is required."
    ],
    "location": {
    "city": [
    "The city field is required"
    ],
    "country": [
    "The country field is required"
    ]
    }
    }


    Any default methods available ?
    I am using IlluminateFoundationHttpFormRequest










    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I have a Json object of data as shown below



      {
      "name": "something",
      "location": {
      "city": "some where",
      "country": "some where",

      }
      }


      Rule used to validate Request is



      [
      'name' => 'required',
      'location.city' => 'required',
      'location.country' => 'required'
      ]


      Which returns error message like



      {
      "name": [
      "The name field is required."
      ],
      "location.city": [
      "The location.city field is required."
      ],
      "location.county": [
      "The location.country field is required."
      ]
      }


      How can I format error message as a nested array like the Request.



      {
      "name": [
      "The name field is required."
      ],
      "location": {
      "city": [
      "The city field is required"
      ],
      "country": [
      "The country field is required"
      ]
      }
      }


      Any default methods available ?
      I am using IlluminateFoundationHttpFormRequest










      share|improve this question















      I have a Json object of data as shown below



      {
      "name": "something",
      "location": {
      "city": "some where",
      "country": "some where",

      }
      }


      Rule used to validate Request is



      [
      'name' => 'required',
      'location.city' => 'required',
      'location.country' => 'required'
      ]


      Which returns error message like



      {
      "name": [
      "The name field is required."
      ],
      "location.city": [
      "The location.city field is required."
      ],
      "location.county": [
      "The location.country field is required."
      ]
      }


      How can I format error message as a nested array like the Request.



      {
      "name": [
      "The name field is required."
      ],
      "location": {
      "city": [
      "The city field is required"
      ],
      "country": [
      "The country field is required"
      ]
      }
      }


      Any default methods available ?
      I am using IlluminateFoundationHttpFormRequest







      laravel validation laravel-5.7






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited yesterday

























      asked yesterday









      Ebin Manuval

      605722




      605722
























          3 Answers
          3






          active

          oldest

          votes

















          up vote
          1
          down vote













          In your case , you need to build the error message yourself. you can still use the default messages in the ressources/lang/en/validation messages file.



          $validator = Validator::make($request->all(), [
          'name' => 'required',
          'location.city' => 'required',
          'location.country' => 'required'
          ]);

          if ($validator->fails()) {
          return response()->json($yourOwnFormat,422);
          //you can use $validator->errors() to build it
          }





          share|improve this answer




























            up vote
            0
            down vote













            Is it? Laravel Documentation- Customizing the Error Messages



            public function messages()
            {
            return [
            'location.city' => 'The city field is required',
            'location.county' => 'The county field is required',
            ];
            }





            share|improve this answer





















            • It will only change the message part like The city field is required I need to change the key location.city. Please have a look at my response sample
              – Ebin Manuval
              yesterday


















            up vote
            0
            down vote













            For those who looking for the solution This is how I implemented



            <?php 
            namespace AppHttpRequests;

            use IlluminateContractsValidationValidator;
            use IlluminateFoundationHttpFormRequest;
            use IlluminateHttpExceptionsHttpResponseException;

            class UserStoreRequest extends FormRequest
            {
            public function rules()
            {
            return [
            'name' => 'required',
            'location.city' => 'required'
            'location.country' => 'required'
            ];
            }
            public function attributes()
            {
            return [
            'location.city' => 'City'
            'location.country' => 'Country'
            ];
            }
            protected function failedValidation(Validator $validator)
            {
            $errors = $validator->errors()->getMessages();
            $errors_formated = array();
            foreach ($errors as $key => $value) {
            array_set($errors_formated, $key, $value);
            }
            throw new HttpResponseException(response()->json(['error' => $errors_formated], 422));
            }
            }


            The result of $validator->errors()->getMessages() is just like array_dot() helper function result. So I did the Opposite of array_dot(), also altered my attribute name into pretty name






            share|improve this answer























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














               

              draft saved


              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53203641%2fformat-validation-error-message-as-nested-associative-array%23new-answer', 'question_page');
              }
              );

              Post as a guest
































              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              1
              down vote













              In your case , you need to build the error message yourself. you can still use the default messages in the ressources/lang/en/validation messages file.



              $validator = Validator::make($request->all(), [
              'name' => 'required',
              'location.city' => 'required',
              'location.country' => 'required'
              ]);

              if ($validator->fails()) {
              return response()->json($yourOwnFormat,422);
              //you can use $validator->errors() to build it
              }





              share|improve this answer

























                up vote
                1
                down vote













                In your case , you need to build the error message yourself. you can still use the default messages in the ressources/lang/en/validation messages file.



                $validator = Validator::make($request->all(), [
                'name' => 'required',
                'location.city' => 'required',
                'location.country' => 'required'
                ]);

                if ($validator->fails()) {
                return response()->json($yourOwnFormat,422);
                //you can use $validator->errors() to build it
                }





                share|improve this answer























                  up vote
                  1
                  down vote










                  up vote
                  1
                  down vote









                  In your case , you need to build the error message yourself. you can still use the default messages in the ressources/lang/en/validation messages file.



                  $validator = Validator::make($request->all(), [
                  'name' => 'required',
                  'location.city' => 'required',
                  'location.country' => 'required'
                  ]);

                  if ($validator->fails()) {
                  return response()->json($yourOwnFormat,422);
                  //you can use $validator->errors() to build it
                  }





                  share|improve this answer












                  In your case , you need to build the error message yourself. you can still use the default messages in the ressources/lang/en/validation messages file.



                  $validator = Validator::make($request->all(), [
                  'name' => 'required',
                  'location.city' => 'required',
                  'location.country' => 'required'
                  ]);

                  if ($validator->fails()) {
                  return response()->json($yourOwnFormat,422);
                  //you can use $validator->errors() to build it
                  }






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered yesterday









                  N69S

                  766311




                  766311
























                      up vote
                      0
                      down vote













                      Is it? Laravel Documentation- Customizing the Error Messages



                      public function messages()
                      {
                      return [
                      'location.city' => 'The city field is required',
                      'location.county' => 'The county field is required',
                      ];
                      }





                      share|improve this answer





















                      • It will only change the message part like The city field is required I need to change the key location.city. Please have a look at my response sample
                        – Ebin Manuval
                        yesterday















                      up vote
                      0
                      down vote













                      Is it? Laravel Documentation- Customizing the Error Messages



                      public function messages()
                      {
                      return [
                      'location.city' => 'The city field is required',
                      'location.county' => 'The county field is required',
                      ];
                      }





                      share|improve this answer





















                      • It will only change the message part like The city field is required I need to change the key location.city. Please have a look at my response sample
                        – Ebin Manuval
                        yesterday













                      up vote
                      0
                      down vote










                      up vote
                      0
                      down vote









                      Is it? Laravel Documentation- Customizing the Error Messages



                      public function messages()
                      {
                      return [
                      'location.city' => 'The city field is required',
                      'location.county' => 'The county field is required',
                      ];
                      }





                      share|improve this answer












                      Is it? Laravel Documentation- Customizing the Error Messages



                      public function messages()
                      {
                      return [
                      'location.city' => 'The city field is required',
                      'location.county' => 'The county field is required',
                      ];
                      }






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered yesterday









                      Mou Hsiao

                      344




                      344












                      • It will only change the message part like The city field is required I need to change the key location.city. Please have a look at my response sample
                        – Ebin Manuval
                        yesterday


















                      • It will only change the message part like The city field is required I need to change the key location.city. Please have a look at my response sample
                        – Ebin Manuval
                        yesterday
















                      It will only change the message part like The city field is required I need to change the key location.city. Please have a look at my response sample
                      – Ebin Manuval
                      yesterday




                      It will only change the message part like The city field is required I need to change the key location.city. Please have a look at my response sample
                      – Ebin Manuval
                      yesterday










                      up vote
                      0
                      down vote













                      For those who looking for the solution This is how I implemented



                      <?php 
                      namespace AppHttpRequests;

                      use IlluminateContractsValidationValidator;
                      use IlluminateFoundationHttpFormRequest;
                      use IlluminateHttpExceptionsHttpResponseException;

                      class UserStoreRequest extends FormRequest
                      {
                      public function rules()
                      {
                      return [
                      'name' => 'required',
                      'location.city' => 'required'
                      'location.country' => 'required'
                      ];
                      }
                      public function attributes()
                      {
                      return [
                      'location.city' => 'City'
                      'location.country' => 'Country'
                      ];
                      }
                      protected function failedValidation(Validator $validator)
                      {
                      $errors = $validator->errors()->getMessages();
                      $errors_formated = array();
                      foreach ($errors as $key => $value) {
                      array_set($errors_formated, $key, $value);
                      }
                      throw new HttpResponseException(response()->json(['error' => $errors_formated], 422));
                      }
                      }


                      The result of $validator->errors()->getMessages() is just like array_dot() helper function result. So I did the Opposite of array_dot(), also altered my attribute name into pretty name






                      share|improve this answer



























                        up vote
                        0
                        down vote













                        For those who looking for the solution This is how I implemented



                        <?php 
                        namespace AppHttpRequests;

                        use IlluminateContractsValidationValidator;
                        use IlluminateFoundationHttpFormRequest;
                        use IlluminateHttpExceptionsHttpResponseException;

                        class UserStoreRequest extends FormRequest
                        {
                        public function rules()
                        {
                        return [
                        'name' => 'required',
                        'location.city' => 'required'
                        'location.country' => 'required'
                        ];
                        }
                        public function attributes()
                        {
                        return [
                        'location.city' => 'City'
                        'location.country' => 'Country'
                        ];
                        }
                        protected function failedValidation(Validator $validator)
                        {
                        $errors = $validator->errors()->getMessages();
                        $errors_formated = array();
                        foreach ($errors as $key => $value) {
                        array_set($errors_formated, $key, $value);
                        }
                        throw new HttpResponseException(response()->json(['error' => $errors_formated], 422));
                        }
                        }


                        The result of $validator->errors()->getMessages() is just like array_dot() helper function result. So I did the Opposite of array_dot(), also altered my attribute name into pretty name






                        share|improve this answer

























                          up vote
                          0
                          down vote










                          up vote
                          0
                          down vote









                          For those who looking for the solution This is how I implemented



                          <?php 
                          namespace AppHttpRequests;

                          use IlluminateContractsValidationValidator;
                          use IlluminateFoundationHttpFormRequest;
                          use IlluminateHttpExceptionsHttpResponseException;

                          class UserStoreRequest extends FormRequest
                          {
                          public function rules()
                          {
                          return [
                          'name' => 'required',
                          'location.city' => 'required'
                          'location.country' => 'required'
                          ];
                          }
                          public function attributes()
                          {
                          return [
                          'location.city' => 'City'
                          'location.country' => 'Country'
                          ];
                          }
                          protected function failedValidation(Validator $validator)
                          {
                          $errors = $validator->errors()->getMessages();
                          $errors_formated = array();
                          foreach ($errors as $key => $value) {
                          array_set($errors_formated, $key, $value);
                          }
                          throw new HttpResponseException(response()->json(['error' => $errors_formated], 422));
                          }
                          }


                          The result of $validator->errors()->getMessages() is just like array_dot() helper function result. So I did the Opposite of array_dot(), also altered my attribute name into pretty name






                          share|improve this answer














                          For those who looking for the solution This is how I implemented



                          <?php 
                          namespace AppHttpRequests;

                          use IlluminateContractsValidationValidator;
                          use IlluminateFoundationHttpFormRequest;
                          use IlluminateHttpExceptionsHttpResponseException;

                          class UserStoreRequest extends FormRequest
                          {
                          public function rules()
                          {
                          return [
                          'name' => 'required',
                          'location.city' => 'required'
                          'location.country' => 'required'
                          ];
                          }
                          public function attributes()
                          {
                          return [
                          'location.city' => 'City'
                          'location.country' => 'Country'
                          ];
                          }
                          protected function failedValidation(Validator $validator)
                          {
                          $errors = $validator->errors()->getMessages();
                          $errors_formated = array();
                          foreach ($errors as $key => $value) {
                          array_set($errors_formated, $key, $value);
                          }
                          throw new HttpResponseException(response()->json(['error' => $errors_formated], 422));
                          }
                          }


                          The result of $validator->errors()->getMessages() is just like array_dot() helper function result. So I did the Opposite of array_dot(), also altered my attribute name into pretty name







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited yesterday

























                          answered yesterday









                          Ebin Manuval

                          605722




                          605722






























                               

                              draft saved


                              draft discarded



















































                               


                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53203641%2fformat-validation-error-message-as-nested-associative-array%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest




















































































                              Popular posts from this blog

                              Schultheiß

                              Verwaltungsgliederung Dänemarks

                              Liste der Kulturdenkmale in Wilsdruff