Php Laravel身份验证-不同表中的电子邮件
我有两张桌子: 人员:Php Laravel身份验证-不同表中的电子邮件,php,laravel,laravel-5,laravel-authentication,Php,Laravel,Laravel 5,Laravel Authentication,我有两张桌子: 人员: id name email phone person_type_id 使用者 您能告诉我如何使Laravel(5.8)的内置身份验证系统在对用户进行身份验证时使用persons表中的email字段吗?仅供参考,guard provider的值必须是users您可以创建自定义用户提供程序(从Lightning\Auth\EloquentUserProvider继承)并覆盖retrieveByCredentials方法 托马斯的建议帮助我解决了这个问题。如果
id name email phone person_type_id
使用者
您能告诉我如何使Laravel(5.8)的内置身份验证系统在对用户进行身份验证时使用persons表中的email字段吗?仅供参考,guard provider的值必须是users您可以创建自定义用户提供程序(从
Lightning\Auth\EloquentUserProvider
继承)并覆盖retrieveByCredentials
方法
托马斯的建议帮助我解决了这个问题。如果它对任何人都有帮助,以下是我的代码: 我创建了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();
}
}
在config/auth.php内部
'providers' => [
'users' => [
'driver' => 'custom_user_provider',
'model' => App\User::class,
'method_to_email_model' => 'person',
],
],
最后在App\User.php(用户模型)中
您可以在auth-config文件中更改默认用户模型,但我仍然认为它不起作用,因为它要求电子邮件和密码在同一个模型中。唯一的另一种方法是创建自定义保护以覆盖Larvels默认值
Auth::provider('custom_user_provider', function ($app, array $config) {
return new CustomUserProvider($app['hash'], $config['model'], $config['method_to_email_model']);
});
'providers' => [
'users' => [
'driver' => 'custom_user_provider',
'model' => App\User::class,
'method_to_email_model' => 'person',
],
],
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');
}