'Empty array when passed to response()->json

I have a method in parent class

Controller.php

public function invalidError($errors = [], $code = 422)
{
    return response()->json([
        'errors' => $errors
    ], $code);
}

I am passing this method the following:

if($validator->fails()) {
    return $this->invalidError([
        array('key' => 'Some key')
    ]);
}

When the response comes in the errors message is always empty array like the following:

{
    "errors": []
}

What am I missing?



Solution 1:[1]

To get the errors array from a validator, use failed()

if($validator->fails()) {
    return $this->invalidError($validator->failed());
}

If you wants the messages from the failed rules use messages()

if($validator->fails()) {
    return $this->invalidError($validator->messages());
}

For more information, you can check the documentation

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 N69S