How to customize my Validator’s return key in the Laravel?

Asked

Viewed 62 times

2

Currently my Validator returns as key the field that did not pass the validation, I wonder if it has to change to a generic name, as "errors" so I can browse the frontend.

Follow the Validator:

protected function create(Request $data)
    {

        $messages =[
            'nome.required'=> 'Precisamos saber o seu nome, preencha por favor',
            'email.required'=> 'Precisamos saber o seu nome, preencha por favor',
            'senha.required'=> 'Você precisa preencher uma senha para efetuar o cadastro.',
            'email.unique'=> 'Opa, esse email ja foi cadastrado, coloque outro.'
        ];

        $validator = Validator::make($data->all(), [
           'email' => 'required|email|unique:users',
           'nome' => 'required|string|max:50',
           'senha' => 'required'
       ], $messages);

        if ($validator->fails()) {
            return response()->json($validator->errors(), 422);
        }

        return User::create([
            'nome' => $data['nome'],
            'email' => $data['email'],
            'telefone' => $data['telefone'],
            'usuario_anjo' => $data['usuario_anjo'],
            'senha' => Hash::make($data['senha']),
        ]);        
    }
}

In case I get:

{"email":["Opa, esse email ja foi cadastrado, coloque outro."]}

How can I switch to "error" ?

  • And what keeps you from going through the front end with the current key?

  • Can you tell why you want to change it?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.