Problem to validate a record already inserted in my BD with Ajax Laravel 5.2

0

I have a form and in which I enter 1 Email which in my BD I put the field as Unique the problem that arises is when reloading a record with the same email I get the SQL error that the field is already registered, but I would like to be able to validate that field with Ajax so that I do not miss that error and I am really new with this from Ajax and Laravel 5.2

    <form method="POST" action="correcto" name="formulario">
    <label>Correo electrónico</label>
    <input type="email" name="email" id="email" class="form-control">
    <button class"btn" type="submit" value="enviar"></button>
    </form>

This is my route

Route::post('correcto', 'RegistroController@recibir');

This is my driver where I enter the record to my BD

public function recibir (Request $request){
$email = $request->input('email');
$guardado = new Registros;
$guardado->email = $email;
}

I have researched a bit and I am seeing more or less the structure that should form the request with Ajax but I do not know how to structure everything

    
asked by Bahamut4321 09.08.2018 в 18:00
source

2 answers

1

You can do the validation in the same request that you are sending through the validator that brings Laravel, for it is enough to add this to the code that you have in your controller:

 //Creamos las reglas de validación
   $rules = [
        'email'      => 'unique'
   ];
  // Ejecutamos el validador, en caso de que falle devolvemos la respuesta
   $validator = \Validator::make($request->all(), $rules);
   if ($validator->fails())
       return \Response::json([
           'error'  => $validator->errors()->all()
       ],422);
   }

Staying your code this way:

public function recibir(Request $request){
  $rules = [
            'email'      => 'unique'
         ];
  $validator = \Validator::make($request->all(), $rules);
       if ($validator->fails())
           return \Response::json([
               'error'  => $validator->errors()->all()
           ],422);
       }
  $email = $request->input('email');
  $guardado = new Registros;
  $guardado->email = $email;
}

Now if you want to strictly make an Ajax request to validate the email before sending the whole form, just ignore all the above, take the email (you can use JQuery for it) and send it to the server to do the respective one validation. Here is an example of an Ajax structure using JQuery that you can use to send it to your Laravel server:

var email = $('#email').val();
$.ajax({
    url: 'tu/url/' + email,
    type: "GET", //Basta realizar una petición GET para hacer una consulta de validación
    success: function(response){
      //Tu código tras verificar que esté todo OK (Response 200)
    },
    error: function(response){
      //Tu código en caso de que haya error (por email repetido, etc)
      //IMPORTANTE: Devolver un código de respuesta diferente 
      // de 200 para que entre en esta función.
    }
});

I hope I have helped you with your problem. Greetings :)

    
answered by 09.08.2018 / 18:47
source
0

Hi, what you proposed to me has helped me a lot, I based more on the second option only now I change a little bit my url with which I try to validate if there is that mail in the BD or not and at the time of executing it always marks me that it is correct when I should identify that the mail already exists

I leave the code

this is my script

<script>
       function validarCorreo(){
         var email = $('#email').val();
           $.ajax({
           url:'validar-correo/{email}',
           type: "GET",
           success: function(response){
                 alert('Correcto');     
          },
           error: function(response){
         }
       });
       }
     </script>

This is my controller with whom I try to do the validation inside the BD

public function validarUsuario ($email){
    //$correo = Registros::where($email, '=>', 'email');
    $correo = Registros::where('email', $email)->first();
              //if ($correo == 'email'){
                if ($correo){
                return response()->json(['error'=>'El correo ya existe'],422);
              }else{
                return response()->json(['success'=>'El correo no existe'],200);
              }

          } 

This is my route that I am using

Route::get('validar-correo/{email}' , 'RegistroController@validarUsuario');

and this is my input

<label>Correo electrónico</label>
                           <input type="email" name="email" id="email"   class="form-control" placeholder="[email protected]" 
                           onchange="validarCorreo()" required >
                           <div id="respuesta" class="col-lg-5"></div>

Thank you very much Erick Duran for taking the time to help me solve my problem.

    
answered by 10.08.2018 в 00:23