2

I want to validate the values of an array of objects in Laravel which I pass through the request from the client side (encoded).

First of all, I decode the values passed through the request then validate to check it is null or not.

This is my code

$request->request->set('shopping_list', array_map(function ($arr) {
    return json_decode($arr);
}, $request->shopping));

$validator = Validator::make($request->toArray(), [
    'shopping_list' => ['required'],
    'shopping_list.*' => ['required'],
    'shopping_list.*.store' => ['required'],
    'shopping_list.*.item' => ['required'],
    'shopping_list.*.quantity' => ['required'],
    'shopping_list.*.brand' => ['required'],
    'shopping_list.*.size' => ['required'],
]);

if (count($validator->errors()) > 0) {
    return Response::json($validator->errors()->first(), 422);
}

Unexpectedly the server is returning no error messages. When I return $request->all() or $request->toArray(), after the validation has been done, I am getting the values as follow

Nullified Response

If I return it before the validation takes place, I am getting a response like this

Response from the server

How can I fix this issue and validate the items?

7
  • Have you tried ['required', 'string'] validation rules? Commented Mar 18, 2019 at 12:35
  • @thefallen Tried. Still the same issue :( Commented Mar 18, 2019 at 12:37
  • Your input is not an array, it is a JSON string. I'm not sure of Laravel by default casts the JSON string to an array then runs the validation or not but that is your issue. Commented Mar 18, 2019 at 12:46
  • @Script47 But I am encoding it to an array. Even if it is not an array the validator should return an error message. Commented Mar 18, 2019 at 12:47
  • 1
    @Conor and if you did return json_decode($arr, true);, does it work? Commented Mar 18, 2019 at 12:49

2 Answers 2

1

As per my suggestion, when using json_decode you can force the JSON string to be returned as associative array by passing true as the second parameter. You were trying to run the validation flags built for arrays on objects.

Note: toArray doesn't convert your JSON to arrays or objects, it simply converts all the properties passed from an object ($request->my_input) to an assoc array.

Sign up to request clarification or add additional context in comments.

Comments

0

As a "not good advise". You can call $request->toArray() (and save data in in some variable) before Validator::make(....

1 Comment

That is not making any difference in the output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.