在您的auth.php文件中,爲提供者數組添加提供程序以定義警衛。
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
//'provider' => 'employees'
],
'api' => [
'driver' => 'token',
'provider' => 'users',
//'provider' => 'employees'
],
'employees' => [
'driver' => 'session',
'provider' => 'employees',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'employees' => [
'driver' => 'eloquent',
'model' => App\Employees::class,
],
],
如果你使用2種不同的模型進行身份驗證,就像上面那樣。如果您使用相同的模型根據用戶角色進行身份驗證,請爲員工和用戶提供相同的模型。
創建員工登錄路線。
Route::get('/employee/login','Auth\[email protected]')->name('employee.login');
Route::post('/employee/login','Auth\[email protected]')->name('employee.login.submit');
創建EmployeeLoginController
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
class EmployeeLoginController extends Controller
{
public function __construct()
{
$this->middleware('guest:employee');
}
public function showLoginForm()
{
return view('auth.employee-login');
}
public function login(Request $request)
{
// Validate the form data
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
// Attempt to log the user in
if (Auth::guard('employee')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
// if successful, then redirect to their intended location
return redirect()->intended(route('employee.Product.list'));
}
// if unsuccessful, then redirect back to the login with the form data
return redirect()->back()->withInput($request->only('email'));
}
}
,如果您使用的是2個不同的模型像上面做的。如果您使用的是相同的模型來驗證基於角色只是角色的嘗試方法中添加下列檢查
attempt(['email' => $request->email, 'password' => $request->password, 'role' => 'employee'], $request->remember))
然後在你的應用程序\異常文件夾添加修改handler.php文件未認證梅索德
保護功能未認證用戶($請求的AuthenticationException $除外)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
$guard = array_get($exception->guards(),0);
switch ($guard) {
case 'admin':
$login = 'admin.login';
break;
case 'employee':
$login = 'employee.login';
break;
default:
$login = 'login';
break;
}
return redirect()->guest(route($login));
}
這裏其實你是$登錄變量被用來重定向到你想,如果用戶沒有通過驗證的URL。
最後在您的應用\ middleware \ RedirectIfAuthenticated.php文件中刪除句柄方法並添加以下內容。
public function handle($request, Closure $next, $guard = null)
{
switch ($guard) {
case 'admin':
if (Auth::guard($guard)->check()) {
return redirect()->route('admin.index');
}
break;
case 'employee':
if (Auth::guard($guard)->check()) {
return redirect()->route('employee.dashboard');
}
break;
default:
if (Auth::guard($guard)->check()) {
return redirect('/');
}
break;
}
return $next($request);
}
在這裏,您正在重定向用戶,如果他們通過身份驗證。
爲更好地理解檢查這個video.This工程在5.3和5.4這將幫助你瞭解所有這些工作。
Youtube link