title: Laravel Ajax Login
body: <p>I am trying to log in a user with Ajax. I used the following code. But the problem is I can see the validation Error but when I tried to check <code>username</code> &amp; <code>password</code> with existing database I got following Error:</p>
  
  <blockquote>
    <p>Uncaught TypeError: Cannot use 'in' operator to search for 'length' in
    Sorry User not found</p>
  </blockquote>
  
  <p>How can I successfully log in a user by avoiding above error?</p>
  
  <p><strong>Login controller:</strong></p>
  
  <pre><code>protected function login(Request $request)
  {
      $validator = Validator::make($request-&gt;all(), [
         'email' =&gt; 'required|email',
          'password' =&gt; 'required',
      ]);
  
      if ($validator-&gt;passes()) {
          if (auth()-&gt;attempt(array('email' =&gt; $request-&gt;input('email'),
            'password' =&gt; $request-&gt;input('password')),true))
          {
              return response()-&gt;json('success');
          }
          return response()-&gt;json(['error'=&gt;'Sorry User not found.']);
      }
  
      return response()-&gt;json(['error'=&gt;$validator-&gt;errors()-&gt;all()]);
  }
  </code></pre>
  
  <p><strong>Ajax Part:</strong></p>
  
  <pre><code>$(document).ready(function() {
      $("#loginBtn").click(function(e) {
  
          $.ajaxSetup({
              headers: {
                  'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
              }
          });
  
          e.preventDefault();
          var email = $("input[name='user_email']").val();
          var password = $("input[name='user_password']").val();
  
          $.ajax({
              url: '{{ route('login') }}',
              type: 'POST',
              data: {
                  email: email,
                  password: password
              },
              success: function(data) {
                  if ($.isEmptyObject(data.error)) {
                      alert(data.success);
                  } else {
                      printErrorMsg(data.error);
                  }
              }
          });
  
      });
  
      function printErrorMsg(msg) {
          $(".print-error-msg-login").find("ul").html('');
          $(".print-error-msg-login").css('display', 'block');
          $.each(msg, function(key, value) {
              $(".print-error-msg-login").find("ul").append('&lt;li&gt;' + value + '&lt;/li&gt;');
          });
      }
  });
  </code></pre>