2017-03-07 125 views
1

我是使用Laravel的新手,我遇到了一些問題。當我使用以下命令創建auth時:如何在Laravel中進行自定義身份驗證查詢

php artisan make:auth 

它會自動創建Auth控制器,視圖和默認用戶表。 在這裏,我想做一些不同的認證。我有這樣一個表:

員工

id | reg_number | name 

用戶

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

當我登錄,我想加入employeesusers表,所以查詢會如:

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

然後,我想使用reg_numberpassword登錄。

我該如何創建類似的東西?

我一直在很多網站上搜索,但還沒有找到任何解決方案。預先感謝您的答案。

+0

https://laravel.io/forum/11-04-2014-laravel-5-how-do-i-create-a-custom-auth-in-laravel-5 – sumit

回答

2

您試圖使用2個不同的表格和2個不同的型號進行驗證,所以通常的Auth::attempt()可能無法按預期工作。但是,您可以執行的操作是自己手動驗證用戶身份。這有什麼安全風險/問題?我不知道。與專家見面。

因此,當用戶使用其reg_number登錄時,您所做的是。你做

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']); 
} 
+0

不滿意,但是,謝謝我使用這種方法:) –

+0

如何在證書爲真時重定向到下一個請求? –

+0

如果有人試圖訪問一個頁面並被重定向到登錄,登錄後你可以執行'return redirect() - > intended('dashboard');'。如果他們只是來登錄,意圖將他們想要去的地方或默認儀表板。 – EddyTheDove