"Undefined property: stdClass :: $ email" laravel

0

My validator returns the errors in the request.

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

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 get:

  

message: "Undefined property: stdClass :: $ email

    
asked by anonymous 15.09.2018 / 16:39

1 answer

0

The correct way to check for an error in email validation is to use the has function:

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

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

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

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

    
15.09.2018 / 20:09