0

I'm trying to authenticate a user through an AJAX call from login.blade.php to LoginController.php, into an authenticate() function. Code is as follows:

Axios code inside login.blade.php

(function(){
   document.querySelector("#loginForm").addEventListener("submit", function(e){
      e.preventDefault()
      axios.post("login/tos", {
          'mail'     : document.querySelector('#mail').value,
          'password' : document.querySelector('#password').value,
          'rememberId' : document.querySelector('#rememberId').value,
      })
      .then(function(response){
          console.log("Success")
          console.log(response)
          clearError()

          location.reload();
      })
    })
})();

After some logical, computation, comes to the authenticate() function in LoginController.php

public function authenticate(LoginUser $request)
  {
    $credentials = [
      "mail" => $request->mail,
      "password" => $request->password
    ];

    echo " |OUTSIDE: ";
    echo ((Auth::check()) ? "AUTH TRUE " : "AUTH FALSE ");

    if (Auth::attempt($credentials)) {

      echo " |INSIDE: ";
      echo ((Auth::check()) ? "AUTH TRUE " : "AUTH FALSE ");

      $request->session()->regenerate();

      return response(['success' => true]);
    }
  }

When I run this code, the page reloads, but the user is not logged in. However, the output to the Console before the page reloads is:

data: " |OUTSIDE: AUTH FALSE |INSIDE: AUTH TRUE "

So my assumption is that the Auth::attempt() works, but the session is deleted. How can I overcome this issue?

I am new to both PHP and JS, and have a limited understanding of sessions. I am grateful for any help I can get.

  • 1
    How do you check if the user is logged in? Does it just reload the login form and does that make you think the user is not logged in? Or is the user actually not logged in? – Loek Feb 07 '20 at 08:28
  • @Loek Hello. I'm using the blade syntax in the login.blade.php page to see if the user is logged in. `@if(Auth::check())

    Logged in

    @else

    Logged out

    @endif`
    – Saadman Shahid Chowdhury Feb 07 '20 at 08:32
  • But to evaluate that blade syntax, you need to actually reload the page. Does the `location.reload()` reload the login page? – Loek Feb 07 '20 at 08:36
  • @Loek Yes, the login page reloads by itself. I have also implemented: `protected $redirectTo = "/top";` So that authenticated users get redirected when they try to go to the login page. – Saadman Shahid Chowdhury Feb 07 '20 at 08:40

0 Answers0