yulianto saparudin
yulianto saparudin

Reputation: 249

How to make a custom auth query in Laravel

I'm new in using Laravel and I have some problems. when I create an auth using the following command:

php artisan make:auth

It automatically creates Auth controller, views, and default user table. Here, I want to make some different auth. I have a table like this:

employees

id | reg_number | name

users

id | name | password | remember_token | employee_id | created_at | updated_at

When I log in, I want to join employees and users table, so the query will be like:

select users.*, employees.reg_number inner join employees on employees.id = users.employee_id

Then, I want to log in using reg_number and password.

How can I create something like that?

I've been searching on many sites, but have not found any solution. Thanks in advance for your answers.

Upvotes: 1

Views: 2251

Answers (1)

EddyTheDove
EddyTheDove

Reputation: 13259

You are trying to authenticate using 2 different tables and 2 different models, so the usual Auth::attempt() might not work as expected. What you could do however, is manually authenticate the user yourself. Any security risks/issues with this ? I can't tell. See with experts.

So what you do is, when a user logs in using their reg_number. You do

public function authenticate(Request $request)
{
    $employee = Employee::where('reg_number', $request->reg_number)->first();

    if ( !$employee ) { //If no employee was found
        return redirect()->back()->withErrors(['reg_number' => 'No such reg_number ']);
    }

    //Assuming you have the relationship setup between employee and user
    //probably a one to one. 
    $user = $employee->user;

    //manually check their password
    //assuming you hash every password when saving the user 
    if (Hash::check($request->password, $user->password)) {
        //password matched. Log in the user 
        Auth::login($user);
        return redirect()->intended('dashboard');
    }

    return redirect()->back()->withErrors(['credentials' => 'Check your credentials']);
}

Upvotes: 2

Related Questions