0

Hello, I would like to know if it is possible for me to transform Laravel's error json into this new json. I'm using Laravel 7

  {
        "message": "The given data was invalid.",
        "errors": {
            "email": [
                "email is already in use"
            ],
            "username": [
                "username is already in use"
            ]
        }
    }

to

{
    "message": "The given data was invalid.",
    "errors": {
        "email": "email is already in use",
        "username": "username is already in use"
    }
}
1
  • Inside of your controller are you using the Validator facade or $request->validate() Commented Feb 16, 2021 at 5:00

2 Answers 2

1

Inside of your controller if you validate your POST request with the Validator facade you can convert the errors into a collection and map over them.

use Illuminate\Support\Facades\Validator;

// Faking the Request array & Commenting out to fail request
$input = [
  // 'username' => 'username',
  // 'password' => 'password',
];

$validator = Validator::make((array) $input, [
  'username' => 'required|unique|string',
  'password' => 'required|string',
]);

if ($validator->fails()) {
  $formatted = collect($validator->errors())->map(function ($error) {
    return $error[0];
  });

  return response()->json([
      'message' => 'The given data was invalid.',
      'errors' => $formatted,
    ], 422);
}
Sign up to request clarification or add additional context in comments.

Comments

0

I'd propose a different approach to the problem.

In you User model you could add a class method called ValidationBook.

public static function ValidationBook($except = [], $append = [])
{
    $book = ['rules' => [], 'messages' => []];
    $book['rules'] = [
        'user.email' => 'required|email|unique:users,email',
        'user.password' => 'required|min:8',
        'user.password_confirmation' => 'required|min:8|same:user.password',
    ];
    $book['messages'] = [
        'user.email.required' => 'The email is required',
        'user.email.email' => 'The email must be a valid email address.',
        'user.email.unique' => 'This email is already in use.',

        'user.password.required' => 'A password is required.',
        'user.password.min' => 'Password musst have at least 8 characters',

        'user.password_confirmation.required' => 'The password confirmation is required.',
        'user.password_confirmation.same' => 'Passwords doesn't match',
    ];
    if (!empty($except)) {
        $except = array_flip($except);
        $book['rules'] = array_diff_key($book['rules'], $except);
    }
    if (!empty($append))
        $book = array_merge_recursive($book, $append);

    return $book;
}

Then, in the controller that receives the request you can simply do:

$vb = User::ValidationBook();
$vb["rules"]["user.client_secret"] .= $request->input("user")["client_id"];
$data = $request->validate($vb["rules"], $vb["messages"]);

Notice that you could define each of the errors, and if something has more than one issues, the response will send all the rules that failed.

Comments

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.