Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Auth::attempt() always false?

I recently started learning Laravel (PHP MVC framework) and I've been having a lot of issues with Authenticating a user with: Auth::attempt($credentials).

I'll put my code snippets below. In my mySQL database I have a record with the following key=>values: id=>1, username=>'admin', password=>'admin', created_at=>0000-00-00 00:00:00, updated_at=>0000-00-00 00:00:00

The Validator passes, but the Auth:attempt always fails.

If the code below and my little explanation isn't enough, please let me know! :-)

Routes.php:

Route::get('login', 'AuthController@showLogin');
Route::post('login', 'AuthController@postLogin');

AuthController:

public function showLogin(){

    if(Auth::check()){
        //Redirect to their home page
    }
    //Not logged in
    return View::make('auth/login');
}

public function postLogin(){

    $userData = array(
        'username' => Input::get('username'),
        'password' => Input::get('password')
    );

    $reqs = array(
        'username' => 'Required',
        'password' => 'Required'
    );

    $validator = Validator::make($userData, $reqs);

    if($validator->passes() && Auth::attempt($userData)){
        return Redirect::to('home');
    }
    return Redirect::to('login')->withInput(Input::except('password'));
}
like image 221
xDranik Avatar asked Aug 01 '13 23:08

xDranik


People also ask

What is Auth :: attempt () in Laravel?

The attempt method accepts an array of key / value pairs as its first argument. The password value will be hashed. The other values in the array will be used to find the user in your database table. So, in the example above, the user will be retrieved by the value of the email column.

What is Auth :: Routes () in Laravel?

Auth::routes() is just a helper class that helps you generate all the routes required for user authentication. You can browse the code here https://github.com/laravel/framework/blob/5.3/src/Illuminate/Routing/Router.php instead.

What does Auth :: check () do?

In other words, Auth::check() calls Auth::user() , gets the result from it, and then checks to see if the user exists. The main difference is that it checks if the user is null for you so that you get a boolean value. As you can see, it calls the user() method, checks if it's null, and then returns a boolean value.

How do I change the login function in Laravel Auth?

In the user login controller in the login module, there are the following codes: $loggedIn = $this->auth->login( [ 'email' => $request->email, 'password' => $request->password, ], (bool) $request->get('remember_me', false) );


1 Answers

I believe the attempt() method will hash the password that is sent in. Seeing as your DB entry's password is 'admin' in plaintext, that would fail. Save your password with Hash::make($password); and i believe your problem should be solved.

like image 90
madsroskar Avatar answered Sep 22 '22 06:09

madsroskar