如何在laravel 10.32.1中验证新用户表

dxxyhpgq  于 2023-11-20  发布在  其他
关注(0)|答案(1)|浏览(98)

此问题在此处已有答案

How do I use the method attempt() - Laravel 7(2个答案)
Laravel guard login(2个答案)
11小时前关闭
我正在开发一个系统,需要验证两个用户('user'和'motoboy')。我已经能够使用auth::attempt验证用户,但是当我向'motoboy'重复它时,它会在'user'表中验证。基本上我想要的是'user'表的auth::attempt和'motoboy'表的auth::attempt。有人能帮助我吗?
My DB:
我的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。我必须创建一个新的提供者吗?我如何做到这一点?

vxf3dgd4

vxf3dgd41#

Laravel有一个为这个用例开发的身份验证保护的概念。它位于config文件夹中的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尝试,如下所示

Auth::guard('motor-boy')->attempt($credentials);


最后,在成功登录后,需要将当前登录会话的默认auth guard设置为moto-boy,如下所示

config()->set('auth.defaults.guard', 'motor-boy');


这确保了当您调用Auth::user()auth()->user()时,默认情况下它将获取经过身份验证的motor-boy配置文件(不指定保护)。
PS:auth()Auth类的facade助手。你也可以在这里阅读更多关于自定义守卫的信息。

相关问题