Search code examples
phplaravelauthenticationlaravel-5.3

Laravel 5.3 Auth::attempt() always returns false


When a new user get registered then it automatically logins, Which is working fine. I am hashing the password like this :

'$newUser->password = bcrypt($request->get('password'));' 

It successfully hashes the password, My users table have password column which is varchar 255. And i have remember_token field too in users table. 'dd($request->all())' returns:

array:3 [
  "email" => "[email protected]"
  "_token" => "QIwnHacApWg3SotAXtoCCMFNK3FYFoFBAv2LSx4c"
  "password" => "adminadmin"
]  

And, The email and password is 100% correct against the users table record. The request is Ajax so i have the following code of JS:

$('.post-btn').click(function(){            
    $.ajax({
        url: '/sign-in',
        type: "post",
        data: {'email':$('input[name=email]').val(), '_token': $('input[name=_token]').val(),'password': $('input[name=password]').val()},
        success: function(data){
            console.log(data);
            window.location = '/';
        }
    });      
}); 

The authenticate method :

public function authenticate(Request $request) {
    $validator = Validator::make($request->all(),
        [
            'email' => "required",
            'password' => 'required'   
        ]
    );

    $user = array('email' => $request->get('email'),'password' => $request->get('password'));
        if (Auth::attempt($user)) {
            $response = array(
                'status' => 'success',
                'msg' => 'Successfully Logins.',
            );
            $user = new \App\User;
            if(Auth::check()) {

            }
            return \Response::json($response);
        } else {
            $response = array(
                'status' => 'failed',
                'msg' => 'Invalid Credentials!',
            );
            return \Response::json($response);
        }
    }

The input field names are correct.

What else I am missing ?


Solution

  • This work for me:

    public function authenticate(Request $request)
    {
        $validator = Validator::make($request->all(),
            [
                'email' => "required",
                'password' => 'required'
    
            ]
        );
        $email = $request->input('email');
        $password = $request->input('password');
        if (Auth::attempt(['email' => $email, 'password' => $password])) {
            // Authentication passed...
            return \Response::json([
                'status' => 'success',
                'msg' => 'Successfully Logins.',
            ]);
        }
        else {
            return \Response::json([
                'status' => 'failed',
                'msg' => 'Invalid Credentials!',
            ]);
        }
    }