Saitimang
Saitimang

Reputation: 33

Laravel Authentication With Two Tables

I am trying to use Laravel's built-in Authentication class. Upon reading it, it seems that it only looks into one table as per the config/auth.php file. As per the doc, I can use syntax like this:

if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
    // The user is active, not suspended, and exists.
}

My concern is, the email column is in my user table while password is in auth table. As I stated above, my understanding of Laravel's authentication is it only looks for one table only. Did I miss something?

Upvotes: 3

Views: 468

Answers (2)

Maxim Lanin
Maxim Lanin

Reputation: 4531

You can authenticate user manually.

  1. Retrieve user from your user table by email with his password from auth table (via simple join or eloquent relations).
  2. Validate that password is correct using \Hash::check($password, $hashedPassword); .
  3. Login user manually usingAuth::login($user); if you are using Eloquent or Auth::loginUsingId($id); if simple DB query.

Docs:

Upvotes: 0

Bogdan
Bogdan

Reputation: 44526

Actually the solution is fantastically simple. You just need to override the getAuthPassword method which is defined in the Authenticatable trait, by adding this to your User model:

public function getAuthPassword()
{
    return \DB::table('auth')->where('user_id', $this->id)->pluck('password');
}

And that's it, now the authentication system will get the password from the auth table before checking if it matches with user input.

Upvotes: 5

Related Questions