How to check if the email already exists in "real time"? Laravel

Asked

Viewed 186 times

-2

I am building an update form. I want that when the user requests an email exchange, first I check that the email is no longer in use. In my html form I have the following field:

<div class="col-4">
    <label for="" class="form-control-label">E-mail:</label>
    <input type="text" name="email" id="email" class="form-control" value="{{Auth::user()->email}}">
</div>

In my controller I use the following code to check if the email already exists:

public function perfil(Request $request)
{   
    $usuarioEmail = User::where('email', '=', $request->input('email'))->first();
    if ($usuarioEmail) {
        if($usuarioEmail->email != Auth::user()->email) //Se o email já estiver cadastrado no banco, verifico se pertence ao usuário que está solicitando a troca

            //Email já utilizado por outro usuário

    }//Se o email não estiver em uso, troco normalmente
    else{User::where('userId', Auth::user()->userId)->update(['email' => $request->input('email')]);}
}

I would like to do this verification in real time without updating the page. How to proceed?

  • 1

    Without updating the page is always JS with ajax

  • 1

    That’s what @Isac said, only with Ajax

1 answer

0


Hey, buddy. All right?

So come on.

Javascript code

<script>
var route = "/verify/email";
var email = document.getElementById("email").value;
var data = {
    "email": email
};

axios.post(route, data).then(res => {
    console.log("O código funcionou perfeitamente");
}).catch(error => {
    console.log("Algo de errado não está certo, verifique novamente seu código");
})

</script>

Route do Laravel

Route::post("/verify/email", PerfilController@perfil);

If your controller does what you promise, just make this request to the Back End and handle the response later in the console.log region, that is, where you have the console.log on .then you would show the response to the user on the front using DOM manipulation, where you have the console.log of the .catch you show an Error message to the customer.

Tip!

The function profile your controller performs two actions, this hurts two principles of good programming practice. I will describe them below and how you can solve them.

Principle of sole responsibility

Each function has a single responsibility, that is, you should have a function that checks if the e-mail is already being used and another function that performs the e-mail update in the database.

Access to the database must be in the Model

Any and all queries must be performed by the Model, that is, these two functions that I told you to build must be built in the Model and be called in the controller. It is not the function of the controller to perform queries or changes in the database! The controller only receives a request ($request), can call functions that have the responsibility to perform other actions and finally returns a response.

Any questions just contact.

Hugs.

Browser other questions tagged

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