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'));
}
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.
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.
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.
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) );
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With