I would like to change password field in database when using Laravel authentication. I want my column in users
table has name passwd
and not password
. I tried to run something like this:
Auth::attempt(array(
'user_name' => 'admin',
'passwd' => 'hardpass',
));
but it doesn't work.
I also tried to add in User
model the following function:
public function getAuthPassword() {
return $this->passwd;
}
but it also changes nothing. User is still not being authenticated. Is it possible in Laravel to change password field name in database ?
Information
You can change easy all other fields in database and use them for authentication. The only problem is with
password
field.In fact
password
field is in some way hard coded in Laravel (but not the way many think) so you cannot just pass array as you passed in your question.By default if you pass array to
attempt
(and probably other Auth functions likevalidate
oronce
) if you do it this way:default Eloquent driver will run the following query:
After getting this data from database it will compare password you gave with password property for User object that was created.
But if you simply use:
the following query will be run:
and no user will be found in database (in
passwd
you store hashed password). This is because Eloquent removes from querypassword
but use any other data to run query. Also if you try here to use'passwd' => Hash:make($data['password'])
although user will be found, comparing password won't work.Solution
Solution is quite easy. You need to run
Auth::attempt
like this:As you see you still pass
password
as key (although this column doesn't exits inusers
table) because only this way Eloquent driver won't use it for building query.Now in
User
model (app/models/User.php
) file you need to add the following function:As you see you use here the column that really exists in database:
passwd
.Using it this way you can have column with password named anything you want and you can still use default Eloquent driver for it.
Sample data to test
I've created very simple test for it.
You just need to replace your
app/routes.php
file with the following:app/config/database.php
/db
url for examplehttp://localhost/yourprojectname/db
just to create users table./
url for examplehttp://localhost/yourprojectname/
- as you see user is logged in even if inusers
table in database you don't have anypassword
column (data for authentication has been passed as strings without any forms but of course in real application you will add them) . You can run this url once more time - as you see user is still logged so it is working as expected.Log out
link, you will be logged outLaravel 5 changes for above
This solution was tested in Larave 4.2.9 (everything as above) and also in Laravel 5. In Laravel5 everything works the same but you need of course edit files in different paths:
User
model is inapp/User.php
fileapp/Http/routes.php
fileconfig/database.php
file