【问题标题】:Database connection [users] not configured未配置数据库连接 [用户]
【发布时间】:2021-09-08 17:26:39
【问题描述】:

我收到 InvalidArgumentException Database connection [users] not configured. http://127.0.0.1:8000/register 错误,提交注册表时,使用 Laravel Auth。我的 Laravel 版本是 6.17.1

.env 文件

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

Auth/RegisterController.php 文件

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:20'],
            'surname' => ['required', 'string', 'max:30'],
            'age' => ['required', 'integer', 'max:100'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users.email'],
            'password' => ['required', 'string', 'min:6'],
            'confirm' => ['required', 'string', 'same:password']
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        date_default_timezone_set("Asia/Yerevan");
        $created = date('Y-m-d H:i:s');
        return User::create([
            'name' => $data['name'],
            'surname'=> $data['surname'],
            'age' => $data['age'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'created_at' => $created
        ]);
    }
}

app/User.php 文件

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;


    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'surname', 'age', 'email', 'password', 'code', 'ban', 'ban_reason', 'created_at', 'image', 'role', 'confirmed'
    ];
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'code', 'confirmed'
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

用户表迁移文件

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name', 20);
            $table->string('surname', 30);
            $table->integer('age');
            $table->string('image', 255);
            $table->string('email', 255);
            $table->string('password', 255);
            $table->integer('code')->default(0);
            $table->string('ban', 255);
            $table->string('ban_reason', 255);
            $table->string('role', 255)->default("user");
            $table->boolean('confirmed')->default(false);
            $table->dateTime('created_at');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

config/database.php 文件

<?php

use Illuminate\Support\Str;

return [

    /*
    |--------------------------------------------------------------------------
    | Default Database Connection Name
    |--------------------------------------------------------------------------
    |
    | Here you may specify which of the database connections below you wish
    | to use as your default connection for all database work. Of course
    | you may use many connections at once using the Database library.
    |
    */

    'default' => env('DB_CONNECTION', 'mysql'),

    /*
    |--------------------------------------------------------------------------
    | Database Connections
    |--------------------------------------------------------------------------
    |
    | Here are each of the database connections setup for your application.
    | Of course, examples of configuring each database platform that is
    | supported by Laravel is shown below to make development simple.
    |
    |
    | All database work in Laravel is done through the PHP PDO facilities
    | so make sure you have the driver for your particular database of
    | choice installed on your machine before you begin development.
    |
    */

    'connections' => [

        'sqlite' => [
            'driver' => 'sqlite',
            'url' => env('DATABASE_URL'),
            'database' => env('DB_DATABASE', database_path('database.sqlite')),
            'prefix' => '',
            'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
        ],

        'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            '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', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

        'pgsql' => [
            'driver' => 'pgsql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '5432'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'prefix_indexes' => true,
            'schema' => 'public',
            'sslmode' => 'prefer',
        ],

        'sqlsrv' => [
            'driver' => 'sqlsrv',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '1433'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'prefix_indexes' => true,
        ],

    ],

    /*
    |--------------------------------------------------------------------------
    | Migration Repository Table
    |--------------------------------------------------------------------------
    |
    | This table keeps track of all the migrations that have already run for
    | your application. Using this information, we can determine which of
    | the migrations on disk haven't actually been run in the database.
    |
    */

    'migrations' => 'migrations',

    /*
    |--------------------------------------------------------------------------
    | Redis Databases
    |--------------------------------------------------------------------------
    |
    | Redis is an open source, fast, and advanced key-value store that also
    | provides a richer body of commands than a typical key-value system
    | such as APC or Memcached. Laravel makes it easy to dig right in.
    |
    */

    'redis' => [

        'client' => env('REDIS_CLIENT', 'phpredis'),

        'options' => [
            'cluster' => env('REDIS_CLUSTER', 'redis'),
            'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
        ],

        'default' => [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', '6379'),
            'database' => env('REDIS_DB', '0'),
        ],

        'cache' => [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', '6379'),
            'database' => env('REDIS_CACHE_DB', '1'),
        ],

    ],

];

auth.php 文件

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
            'hash' => false,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
            'throttle' => 60,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Password Confirmation Timeout
    |--------------------------------------------------------------------------
    |
    | Here you may define the amount of seconds before a password confirmation
    | times out and the user is prompted to re-enter their password via the
    | confirmation screen. By default, the timeout lasts for three hours.
    |
    */

    'password_timeout' => 10800,

];

我尝试过更改 .env 文件,清除缓存和配置,但没有结果。

UPD1: dd(config('database'));

array:4 [▼
  "default" => "mysql"
  "connections" => array:4 [▼
    "sqlite" => array:5 [▶]
    "mysql" => array:15 [▼
      "driver" => "mysql"
      "url" => null
      "host" => "127.0.0.1"
      "port" => "3306"
      "database" => "geeknews"
      "username" => "root"
      "password" => ""
      "unix_socket" => ""
      "charset" => "utf8mb4"
      "collation" => "utf8mb4_unicode_ci"
      "prefix" => ""
      "prefix_indexes" => true
      "strict" => true
      "engine" => null
      "options" => []
    ]
    "pgsql" => array:12 [▶]
    "sqlsrv" => array:10 [▶]
  ]
  "migrations" => "migrations"
  "redis" => array:4 [▶]
]

【问题讨论】:

  • 这能回答你的问题吗? Database not configured laravel during migration
  • @MuhammadDyasYaskur 不,表创建成功,迁移没有问题。
  • 你尝试过里面的步骤吗??
  • 你的一个模型(如果不是用户模型)有这一行`protected $connection = 'users';`删除它或将它设置为mysql。还要验证 .env DB_CONNECTION=mysql
  • 请回复config/auth.php的内容

标签: php laravel


【解决方案1】:

我有同样的错误,它是由于错误的验证角色而发生的。

我收到了这个错误:

{
"message": "Database connection [users] not configured.",
"exception": "InvalidArgumentException", ... 
}

再次检查您的验证规则,尤其是 [unique] 规则。

我的代码错误:

$rules = [
         'username'  => 'required|min:8|unique:users.username,'.$request->input('user-id')
];

正确的:

$rules = [
         'username'  => 'required|min:8|unique:users,username,'.$request->input('user-id')
];

您在“Auth/RegisterController.php”中有同样的问题: 替换这个:

protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => ['required', 'string', 'max:20'],
        'surname' => ['required', 'string', 'max:30'],
        'age' => ['required', 'integer', 'max:100'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users.email'],
        'password' => ['required', 'string', 'min:6'],
        'confirm' => ['required', 'string', 'same:password']
    ]);
}

有了这个:

    protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => ['required', 'string', 'max:20'],
        'surname' => ['required', 'string', 'max:30'],
        'age' => ['required', 'integer', 'max:100'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email'],
        'password' => ['required', 'string', 'min:6'],
        'confirm' => ['required', 'string', 'same:password']
    ]);
}

【讨论】:

  • 出现这个错误后,我关闭了项目,但是下一个项目出现了同样的问题,因为你注意到的验证,我在一个月前修复了它,一切正常,谢谢你的回答.没有办法回到之前的项目,所以我没有回答我的问题。
【解决方案2】:

首先运行php artisan config:cache &amp; php artisan cache:clear,然后重试。如果问题仍然存在,您可以在 Users 模型中手动指定数据库连接:

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;


    # database connection
    protected $connection = 'mysql';


    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'surname', 'age', 'email', 'password', 'code', 'ban', 'ban_reason', 'created_at', 'image', 'role', 'confirmed'
    ];
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'code', 'confirmed'
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}


通常这不是必需的,因为您的应用程序使用mysql 作为默认连接,尽管我不知道您的环境。问题可能在任何地方。希望这会有所帮助。

【讨论】:

  • dd (config('database')) 返回数组:4 [▼ "default" => "mysql" "connections" => array:4 [▶] "migrations" => "migrations" "redis" => 数组:4 [▶] ]
【解决方案3】:

我在 Laravel 8.x 上遇到了同样的错误,为了解决您的问题,您必须将电子邮件输入的验证规则从 unique:users.email 更改为 unique:users,email,如下所示:

protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => ['required', 'string', 'max:20'],
        'surname' => ['required', 'string', 'max:30'],
        'age' => ['required', 'integer', 'max:100'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email'],
        'password' => ['required', 'string', 'min:6'],
        'confirm' => ['required', 'string', 'same:password']
    ]);
}

【讨论】:

    【解决方案4】:

    尝试改变

    DB_CONNECTION=mysql
    

    DB_CONNECTION=localhost
    

    【讨论】:

    • 错误答案,localhost 应该是DB_HOST 上的主机,而不是DB_CONNECTION
    【解决方案5】:

    3

    我有同样的错误,它是由于错误的验证角色而发生的。

    未配置数据库连接 [用户]。

    再次检查您的验证规则,尤其是(唯一)规则。

    我也遇到了这个问题,搜了很多,上面这位朋友说的这个答案真的是对的

    您在验证中输入了错误的代码

    我的代码错误:

    'mobile' => 'required|unique:users.mobile,'. auth()->id(),
    

    正确的:

    'mobile' => 'required|unique:users,mobile,'. auth()->id(),
    

    【讨论】:

    • 我认为您需要尝试解释整个图片,然后正确引用您的参考文献。
    • 你好。看起来您已经复制了已接受答案的某些部分以创建您的答案。请清理并让您的答案独一无二。谢谢。
    • 嗨,埃里克。是的,我复制了您的部分代码。因为我说波斯语和英语不是很好。但我在帖子的一部分中提到了你,并在页面顶部说我们朋友的最佳答案。确认你的答案。我说你给出了最好的答案。
    猜你喜欢
    • 1970-01-01
    • 2022-12-05
    • 2011-01-26
    • 2012-09-16
    • 1970-01-01
    • 2013-12-14
    • 2014-03-06
    • 1970-01-01
    • 2018-02-09
    相关资源
    最近更新 更多