我正在开发一个需要验证两个用户(“user”和“motoboy”)的系统。我已经能够使用 auth::attempt 对用户进行身份验证,但是当我向“motoboy”重复它时,它会在“用户”表中进行身份验证。 基本上我想要的是对“user”表的一次 auth::attempt 以及对“motoboy”表的另一次尝试。有人可以帮助我吗?
我的 MotoboyController
<?php
namespace App\Http\Controllers;
use App\Models\Motoboy;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
class MotoboyController extends Controller
{
public function login()
{
$css = '/assets/css/users/create.css';
$title = 'Motoboy - Login';
return view('motoboys.login', ['css' => $css, 'title' => $title]);
}
public function auth(Request $request): RedirectResponse
{
$credentials = $request->validate([
'email' => ['required', 'email'],
'password' => ['required'],
]);
if (Auth::attempt($credentials)) {
$request->session()->regenerate();
return redirect()->intended(route('dashboard'));
}
return back()->withErrors([
'login' => 'Deu ruim!'
]);
}
我的模型摩托车男孩
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Motoboy extends Authenticatable
{
use HasFactory;
protected $table = 'motoboys';
protected $attributes = ['id_status' => 1];
}
我的代码正在使用用户表对 motoboy 进行身份验证。我必须创建一个新的提供商吗?我该怎么做?
Laravel 有一个为您的用例开发的身份验证防护概念。它位于配置文件夹中的
auth.php
文件中。
向守卫数组中添加一个
motor-boy
守卫
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'admins',
],
'motor-boy' => [
'driver' => 'session',
'provider' => 'motor-boy',
],
...
],
将
motor-boy
守卫提供者添加到提供者数组中。这可确保防护装置根据指定的模型进行身份验证。
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'motor-boy' => [
'driver' => 'eloquent',
'model' => App\Models\Motoboy::class,
],
...
],
接下来是在控制器中使用身份验证尝试,如下所示
Auth::guard('motor-boy')->attempt($credentials);
最后,登录成功后,您需要将当前登录会话的默认身份验证设置为 moto-boy,如下所示
config()->set('auth.defaults.guard', 'motor-boy');
这确保了当您调用
Auth::user()
或 auth()->user()
时,它会默认获取经过身份验证的 motor-boy
配置文件(无需指定守卫)。
PS:
auth()
是Auth
类的外观助手。
我希望这有帮助。
谢谢。