Validating array in laravel requires the key to exist. Remove the key and validation passes












1















I have an items array, sent to the controller as JSON within the items form key.



[{
"sku": "w-hook-as1",
"qty": 2,
"cost_ex_tax": "34.22",
"tax_rate": "0.2"
}]


Here it is converted to an array:



$request->merge(['items' => json_decode($request->items, true)]);


and validated against the rule:



'items.*.sku' =>[
'required',
Rule::exists('products')->where(function ($query) {
$query->where('company_id', Auth::user()->company_id);
})
],


The exists rule does work, if the array key that its validation against exists, assuming the key exists. If I simply send:



[{
"qty": 2,
"cost_ex_tax": "34.22",
"tax_rate": "0.2"
}]


Then the validation passes.



Is there a way I can check that the key exists as well as validate its content? I would have expected that the required check does this, but it does not seem to work.



How to validate array in Laravel? - This answer suggests to validate that it is an array with x number of elements, but still does not check the exact keys I am looking for are there.










share|improve this question



























    1















    I have an items array, sent to the controller as JSON within the items form key.



    [{
    "sku": "w-hook-as1",
    "qty": 2,
    "cost_ex_tax": "34.22",
    "tax_rate": "0.2"
    }]


    Here it is converted to an array:



    $request->merge(['items' => json_decode($request->items, true)]);


    and validated against the rule:



    'items.*.sku' =>[
    'required',
    Rule::exists('products')->where(function ($query) {
    $query->where('company_id', Auth::user()->company_id);
    })
    ],


    The exists rule does work, if the array key that its validation against exists, assuming the key exists. If I simply send:



    [{
    "qty": 2,
    "cost_ex_tax": "34.22",
    "tax_rate": "0.2"
    }]


    Then the validation passes.



    Is there a way I can check that the key exists as well as validate its content? I would have expected that the required check does this, but it does not seem to work.



    How to validate array in Laravel? - This answer suggests to validate that it is an array with x number of elements, but still does not check the exact keys I am looking for are there.










    share|improve this question

























      1












      1








      1








      I have an items array, sent to the controller as JSON within the items form key.



      [{
      "sku": "w-hook-as1",
      "qty": 2,
      "cost_ex_tax": "34.22",
      "tax_rate": "0.2"
      }]


      Here it is converted to an array:



      $request->merge(['items' => json_decode($request->items, true)]);


      and validated against the rule:



      'items.*.sku' =>[
      'required',
      Rule::exists('products')->where(function ($query) {
      $query->where('company_id', Auth::user()->company_id);
      })
      ],


      The exists rule does work, if the array key that its validation against exists, assuming the key exists. If I simply send:



      [{
      "qty": 2,
      "cost_ex_tax": "34.22",
      "tax_rate": "0.2"
      }]


      Then the validation passes.



      Is there a way I can check that the key exists as well as validate its content? I would have expected that the required check does this, but it does not seem to work.



      How to validate array in Laravel? - This answer suggests to validate that it is an array with x number of elements, but still does not check the exact keys I am looking for are there.










      share|improve this question














      I have an items array, sent to the controller as JSON within the items form key.



      [{
      "sku": "w-hook-as1",
      "qty": 2,
      "cost_ex_tax": "34.22",
      "tax_rate": "0.2"
      }]


      Here it is converted to an array:



      $request->merge(['items' => json_decode($request->items, true)]);


      and validated against the rule:



      'items.*.sku' =>[
      'required',
      Rule::exists('products')->where(function ($query) {
      $query->where('company_id', Auth::user()->company_id);
      })
      ],


      The exists rule does work, if the array key that its validation against exists, assuming the key exists. If I simply send:



      [{
      "qty": 2,
      "cost_ex_tax": "34.22",
      "tax_rate": "0.2"
      }]


      Then the validation passes.



      Is there a way I can check that the key exists as well as validate its content? I would have expected that the required check does this, but it does not seem to work.



      How to validate array in Laravel? - This answer suggests to validate that it is an array with x number of elements, but still does not check the exact keys I am looking for are there.







      php laravel validation laravel-validation






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 13 '18 at 18:13









      Adam LambertAdam Lambert

      304111




      304111
























          1 Answer
          1






          active

          oldest

          votes


















          0














          I tried to replicate what you have without the custom Rule so what I did is the following:



          in my blade I have



          <input type="text" name="items" value='[{"sku": "w-hook-as1","qty": 2,"cost_ex_tax": "34.22","tax_rate": "0.2"}, {"qty": 2,"cost_ex_tax": "34.22","tax_rate": "0.2"}]'>


          You can notice here that in my second object I don't have the sku item in the object.
          Then in the controller:



          $arr = request()->merge(['items' => json_decode(request('items'), true)]);

          $validator = Validator::make($arr->all(), [
          'items.*.sku' =>[
          'required'
          ]
          ]);

          dd($validator->fails(), $validator);


          And the response is the following:



          true // this is because the validation fails.
          // and the message bag contains this
          #messages: array:1 [▼
          "items.1.sku" => array:1 [▼
          0 => "The items.1.sku field is required."
          ]
          ]


          So make sure you are not doing anything wrong.



          Print out $request->all() and make sure that your items have the following content:



          "items" => array:2 [▼
          0 => array:4 [▼
          "sku" => "w-hook-as1"
          "qty" => 2
          "cost_ex_tax" => "34.22"
          "tax_rate" => "0.2"
          ]
          1 => array:3 [▼
          "qty" => 2
          "cost_ex_tax" => "34.22"
          "tax_rate" => "0.2"
          ]
          ]


          if not then you need to modify your validation.



          Let me know if I am not following some steps that you do.






          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',
            autoActivateHeartbeat: false,
            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%2f53287159%2fvalidating-array-in-laravel-requires-the-key-to-exist-remove-the-key-and-valida%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            I tried to replicate what you have without the custom Rule so what I did is the following:



            in my blade I have



            <input type="text" name="items" value='[{"sku": "w-hook-as1","qty": 2,"cost_ex_tax": "34.22","tax_rate": "0.2"}, {"qty": 2,"cost_ex_tax": "34.22","tax_rate": "0.2"}]'>


            You can notice here that in my second object I don't have the sku item in the object.
            Then in the controller:



            $arr = request()->merge(['items' => json_decode(request('items'), true)]);

            $validator = Validator::make($arr->all(), [
            'items.*.sku' =>[
            'required'
            ]
            ]);

            dd($validator->fails(), $validator);


            And the response is the following:



            true // this is because the validation fails.
            // and the message bag contains this
            #messages: array:1 [▼
            "items.1.sku" => array:1 [▼
            0 => "The items.1.sku field is required."
            ]
            ]


            So make sure you are not doing anything wrong.



            Print out $request->all() and make sure that your items have the following content:



            "items" => array:2 [▼
            0 => array:4 [▼
            "sku" => "w-hook-as1"
            "qty" => 2
            "cost_ex_tax" => "34.22"
            "tax_rate" => "0.2"
            ]
            1 => array:3 [▼
            "qty" => 2
            "cost_ex_tax" => "34.22"
            "tax_rate" => "0.2"
            ]
            ]


            if not then you need to modify your validation.



            Let me know if I am not following some steps that you do.






            share|improve this answer




























              0














              I tried to replicate what you have without the custom Rule so what I did is the following:



              in my blade I have



              <input type="text" name="items" value='[{"sku": "w-hook-as1","qty": 2,"cost_ex_tax": "34.22","tax_rate": "0.2"}, {"qty": 2,"cost_ex_tax": "34.22","tax_rate": "0.2"}]'>


              You can notice here that in my second object I don't have the sku item in the object.
              Then in the controller:



              $arr = request()->merge(['items' => json_decode(request('items'), true)]);

              $validator = Validator::make($arr->all(), [
              'items.*.sku' =>[
              'required'
              ]
              ]);

              dd($validator->fails(), $validator);


              And the response is the following:



              true // this is because the validation fails.
              // and the message bag contains this
              #messages: array:1 [▼
              "items.1.sku" => array:1 [▼
              0 => "The items.1.sku field is required."
              ]
              ]


              So make sure you are not doing anything wrong.



              Print out $request->all() and make sure that your items have the following content:



              "items" => array:2 [▼
              0 => array:4 [▼
              "sku" => "w-hook-as1"
              "qty" => 2
              "cost_ex_tax" => "34.22"
              "tax_rate" => "0.2"
              ]
              1 => array:3 [▼
              "qty" => 2
              "cost_ex_tax" => "34.22"
              "tax_rate" => "0.2"
              ]
              ]


              if not then you need to modify your validation.



              Let me know if I am not following some steps that you do.






              share|improve this answer


























                0












                0








                0







                I tried to replicate what you have without the custom Rule so what I did is the following:



                in my blade I have



                <input type="text" name="items" value='[{"sku": "w-hook-as1","qty": 2,"cost_ex_tax": "34.22","tax_rate": "0.2"}, {"qty": 2,"cost_ex_tax": "34.22","tax_rate": "0.2"}]'>


                You can notice here that in my second object I don't have the sku item in the object.
                Then in the controller:



                $arr = request()->merge(['items' => json_decode(request('items'), true)]);

                $validator = Validator::make($arr->all(), [
                'items.*.sku' =>[
                'required'
                ]
                ]);

                dd($validator->fails(), $validator);


                And the response is the following:



                true // this is because the validation fails.
                // and the message bag contains this
                #messages: array:1 [▼
                "items.1.sku" => array:1 [▼
                0 => "The items.1.sku field is required."
                ]
                ]


                So make sure you are not doing anything wrong.



                Print out $request->all() and make sure that your items have the following content:



                "items" => array:2 [▼
                0 => array:4 [▼
                "sku" => "w-hook-as1"
                "qty" => 2
                "cost_ex_tax" => "34.22"
                "tax_rate" => "0.2"
                ]
                1 => array:3 [▼
                "qty" => 2
                "cost_ex_tax" => "34.22"
                "tax_rate" => "0.2"
                ]
                ]


                if not then you need to modify your validation.



                Let me know if I am not following some steps that you do.






                share|improve this answer













                I tried to replicate what you have without the custom Rule so what I did is the following:



                in my blade I have



                <input type="text" name="items" value='[{"sku": "w-hook-as1","qty": 2,"cost_ex_tax": "34.22","tax_rate": "0.2"}, {"qty": 2,"cost_ex_tax": "34.22","tax_rate": "0.2"}]'>


                You can notice here that in my second object I don't have the sku item in the object.
                Then in the controller:



                $arr = request()->merge(['items' => json_decode(request('items'), true)]);

                $validator = Validator::make($arr->all(), [
                'items.*.sku' =>[
                'required'
                ]
                ]);

                dd($validator->fails(), $validator);


                And the response is the following:



                true // this is because the validation fails.
                // and the message bag contains this
                #messages: array:1 [▼
                "items.1.sku" => array:1 [▼
                0 => "The items.1.sku field is required."
                ]
                ]


                So make sure you are not doing anything wrong.



                Print out $request->all() and make sure that your items have the following content:



                "items" => array:2 [▼
                0 => array:4 [▼
                "sku" => "w-hook-as1"
                "qty" => 2
                "cost_ex_tax" => "34.22"
                "tax_rate" => "0.2"
                ]
                1 => array:3 [▼
                "qty" => 2
                "cost_ex_tax" => "34.22"
                "tax_rate" => "0.2"
                ]
                ]


                if not then you need to modify your validation.



                Let me know if I am not following some steps that you do.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 13 '18 at 23:56









                nakovnakov

                2,274189




                2,274189






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53287159%2fvalidating-array-in-laravel-requires-the-key-to-exist-remove-the-key-and-valida%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    List item for chat from Array inside array React Native

                    Thiostrepton

                    Caerphilly