📅  最后修改于: 2023-12-03 14:43:46.410000             🧑  作者: Mango
在Laravel中,我们可以很方便地使用多个数据库,但是如何在应用程序中使用这些数据库进行用户验证呢?
在config/database.php
文件中,我们可以指定多个数据库连接,比如:
'connections' => [
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
'pgsql' => [
'driver' => 'pgsql',
'host' => env('DB_PGSQL_HOST', '127.0.0.1'),
'port' => env('DB_PGSQL_PORT', '5432'),
'database' => env('DB_PGSQL_DATABASE', 'forge'),
'username' => env('DB_PGSQL_USERNAME', 'forge'),
'password' => env('DB_PGSQL_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public',
'sslmode' => 'prefer',
],
],
Laravel提供了自带的Illuminate\Auth\EloquentUserProvider
用户验证驱动,但它只支持单一数据库,所以我们需要自己扩展一个用户驱动来支持多个数据库。
我们可以创建一个新的DatabaseUserProvider
类,继承Illuminate\Auth\EloquentUserProvider
类,并在retrieveByCredentials
方法中加入对多个数据库的支持。
namespace App\Auth;
use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
use Illuminate\Support\Arr;
class DatabaseUserProvider extends EloquentUserProvider
{
protected $connections;
public function __construct($connections, $model)
{
$this->connections = $connections;
parent::__construct($this->connections['default'], $model);
}
public function retrieveByCredentials(array $credentials)
{
if (empty($credentials) ||
(count($credentials) === 1 &&
array_key_exists('password', $credentials))) {
return;
}
$query = $this->newModelQuery();
foreach ($credentials as $key => $value) {
if (! Str::contains($key, 'password')) {
$query->orWhere(function ($query) use ($key, $value) {
foreach ($this->connections as $id => $name) {
$query->connection($id)->where($name.'.username', $value);
}
});
}
}
return $query->first();
}
}
在config/auth.php
文件中,我们可以指定使用新的DatabaseUserProvider
类作为用户认证驱动。
'providers' => [
'users' => [
'driver' => 'database',
'model' => App\User::class,
'table' => 'users',
'connections' => [
'default' => 'mysql',
'pgsql' => 'users_pgsql',
],
],
],
现在我们就可以在应用程序中使用多个数据库进行用户验证了。只需要在config/auth.php
文件中指定不同的数据库连接即可。