Laravel 身份验证 - 不同的电子邮件 table

Laravel Authentication - Email in different table

我有两个 table:

人:

id   name   email   phone   person_type_id

用户

id   person_id  password role_id etc...

你能告诉我如何使 Laravel 的 (5.8) 内置身份验证系统使用来自 persons[= 的 email 字段吗25=] table 验证用户时?仅供参考,守卫提供者的价值必须是 users.

您可以创建自定义用户提供程序(继承自 Illuminate\Auth\EloquentUserProvider)并覆盖 retrieveByCredentials 方法。

Laravel Docs - The User Provider Contract

@Thomas 的建议帮我解决了问题。如果它对任何人有帮助,这是我的代码:

我创造了CustomUserProvider.php

<?php

namespace App\Providers;
use Illuminate\Support\Str;
use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Contracts\Hashing\Hasher as HasherContract;

class CustomUserProvider extends EloquentUserProvider { 

private $method_to_email_model;

public function __construct(HasherContract $hasher, $model, $method_to_email_model)
{

    parent::__construct($hasher, $model);

    $this->method_to_email_model = $method_to_email_model;
}

public function retrieveByCredentials(array $credentials)
{

    if (empty($credentials) ||
       (count($credentials) === 1 &&
        array_key_exists('password', $credentials))) {
        return;
    }

    $query = $this->createModel()->newQuery();

    foreach ($credentials as $key => $value) 
    {
        if (Str::contains($key, 'password')) {
            continue;
        }

        if (is_array($value) || $value instanceof Arrayable) {

            $query->with([$this->method_to_email_model => function($q) use($key, $value){
                $q->whereIn($key, $value);
            }]);

        } else {


            $query->with([$this->method_to_email_model => function($q) use($key, $value){
                $q->where($key, $value);
            }]);
        }
    }

    return $query->first();
 }   

}

然后在App\Providers\AuthServiceProvider.php文件中,里面的boot函数:

Auth::provider('custom_user_provider', function ($app, array $config) {
    return new CustomUserProvider($app['hash'], $config['model'], $config['method_to_email_model']);
});

里面 config/auth.php

 'providers' => [ 
    'users' => [
        'driver'                => 'custom_user_provider',
        'model'                 => App\User::class,
        'method_to_email_model' => 'person',
    ],
  ],

终于在 App\User.php(用户模型)

protected $appends = [
    'email', 'first_name', 'last_name'
 ];

public function person()
{
    return $this->belongsTo(Person::class, 'person_id', 'id');
}

public function getEmailAttribute()
{
    return $this->person->getAttribute('email');
}

public function getFirstNameAttribute()
{
    return $this->person->getAttribute('first_name');
}

public function getLastNameAttribute()
{
    return $this->person->getAttribute('last_name');
}