"Undefined Property: stdClass::$email" Laravel

Asked

Viewed 691 times

0

My Validator returns the existing errors in the request.

I would like to check if in the variable I save my errors has the error email to return the correct answer.

I tried something like:

public function register(Request $request)
    {
        $errors = $this->validator($request->all())->errors();

        if(count($errors))
        {
            $obj = json_decode($errors);
            if($obj->email){
                return response(['errors' => 'Este email já está cadastrado no sistema, tente outro.'], 401);
            }else{
                return response(['errors' => $errors],401);
            }
        }

        event(new Registered($user = $this->create($request->all())));

        return response(['mensagem' => "Usuário cadastrado com sucesso!"]);
    }

However, I do receive:

message: "Undefined Property: stdClass::$email

1 answer

0


The correct way to check if there was an error in the e-mail validation is to use the function has:

if ($errors->has('email')) {
    // Código de tratamento
}

You don’t need to use json_decode because the variable $errors is not in Json format.

I suggest you read the documentation on handle errors in validation if you want to manipulate the errors better.

And if you are using this method only to return a message in Portuguese, I suggest you read that to learn how to add translation validation error messages.

Browser other questions tagged

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