MySQL Laravel:如何在数据库中插入第一个用户

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34382043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 21:30:10  来源:igfitidea点击:

Laravel : How do I insert the first user in the database

mysqllaravellaravel-4laravel-seeding

提问by Dom

I am using Laravel (4.2)

我正在使用 Laravel (4.2)

I am working on a project with an authentication system. I need to insert a first user into my users table. I would like to do that directly with a sql command (insert into users....). Because this first user can't be created with the traditional laravel methods.

我正在开发一个带有身份验证系统的项目。我需要将第一个用户插入到我的用户表中。我想直接用 sql 命令(插入用户......)来做到这一点。因为无法使用传统的 Laravel 方法创建第一个用户。

This first user will be identified with the auth::attempts method, after being inserted into the table.

在插入到表中后,第一个用户将使用 auth::attempts 方法进行标识。

How do I insert this user into mysql table?

如何将此用户插入到mysql表中?

something like?

就像是?

insert into  users (login, password) values ('admin', 'crypted password which can be later identified with laravel')

回答by Angel M.

I'm doing it this way:

我是这样做的:

creating seeder with artisan:

与工匠一起创建播种机:

php artisan make:seeder UsersTableSeeder

then you open the file and you enter users:

然后打开文件并输入用户:

use Illuminate\Database\Seeder;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('users')->insert([
            'name' => 'User1',
            'email' => '[email protected]',
            'password' => bcrypt('password'),
        ]);
        DB::table('users')->insert([
            'name' => 'user2',
            'email' => '[email protected]',
            'password' => bcrypt('password'),
        ]);
    }
}

If you want to generate random list of users, you can use factories:

如果要生成随机用户列表,可以使用工厂:

use Illuminate\Database\Seeder;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\User::class, 50)->create();
        /* or you can add also another table that is dependent on user_id:*/
       /*factory(App\User::class, 50)->create()->each(function($u) {
            $userId = $u->id;
            DB::table('posts')->insert([
                'body' => str_random(100),
                'user_id' => $userId,
            ]);
        });*/
    }
}

Then in the file app/database/seeds/DatabaseSeeder.php uncomment or add in run function a line:

然后在文件 app/database/seeds/DatabaseSeeder.php 中取消注释或在运行函数中添加一行:

$this->call(UsersTableSeeder::class);

it will look like this:

它看起来像这样:

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $this->call(UsersTableSeeder::class);
    }
}

At the end you run:

最后你运行:

php artisan db:seed

or

或者

php artisan db:seed --class=UsersTableSeeder

I hope will help someone. PS: this was done on Laravel 5.3

我希望会帮助某人。PS:这是在 Laravel 5.3 上完成的

回答by despotbg

For password, open the terminal on the root of your project. Then write php artisan tinker. Then echo Hash::make('password');

对于密码,请打开项目根目录上的终端。然后写php artisan tinker。然后echo Hash::make('password');

回答by Martin Eckleben

Place the following values in the .envfile.

将以下值放入.env文件中。

INITIAL_USER_PASSWORDHASHis bcryptand has to be generated by the users.

INITIAL_USER_PASSWORDHASHbcrypt,必须由用户生成。

You can use https://bcrypt-generator.com/as a online generator tool to create passwords outside of the application.

您可以使用https://bcrypt-generator.com/作为在线生成器工具在应用程序之外创建密码。

Your application should provide an easier way.

您的应用程序应该提供一种更简单的方法。

You don't want to save cleartextpasswords in the envfile.

您不想在文件中保存明文密码env

INITIAL_USER_NAME=
INITIAL_USER_EMAIL=
INITIAL_USER_PASSWORDHASH=

Then as suggested in the other answers before use a seeder:

然后在使用播种机之前按照其他答案中的建议:

To generate a seeder with composeryou will need to use the following artiasncommand.

要生成播种机,composer您需要使用以下artiasn命令。

php artisan make:seeder UsersTableSeeder

php artisan make:seeder UsersTableSeeder

This command will create a seeder file located in your database/seedsfolder.

此命令将在您的database/seeds文件夹中创建一个播种机文件。

<?php

use Illuminate\Database\Seeder;

class UsersTableSeeder extends Seeder
{
  /**
   * Run the database seeds.
   *
   * @return void
   */
  public function run()
  {
    DB::table('users')->insert([
      'name' => env('INITIAL_USER_NAME'),
      'email' => env('INITIAL_USER_EMAIL'),
      'password' => env('INITIAL_USER_PASSWORDHASH'),
    ]);
  }
}

You will need to edit your database/seeds/DatabaseSeeder.phpand make sure UsersTableSeeder::classis uncommitted inside the method run().

您将需要编辑您的database/seeds/DatabaseSeeder.php并确保UsersTableSeeder::class在方法内未提交run()

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
      $this->call([
        UsersTableSeeder::class
      ]);
    }
}

It is recommended you run the composer dump-autoloadcommand after saving your changes.

建议您composer dump-autoload在保存更改后运行该命令。

You can run all seeds that are inside the DatabaseSeeder.phpfile by running the artisancommand;

您可以DatabaseSeeder.php通过运行artisan命令来运行文件中的所有种子;

php artisan db:seed

php artisan db:seed

You can alternatively use the following to execute only the one seeder by doing the php artisan db:seed --class="UsersTableSeeder"command.

您也可以使用以下php artisan db:seed --class="UsersTableSeeder"命令通过执行命令仅执行一个播种器。

You can also use php artisan migrate:fresh --seedto do a fresh migration of your database tables and seed the table in a single command.

您还可以使用php artisan migrate:fresh --seed对数据库表进行全新迁移并在单个命令中为该表设定种子。

回答by Jammer

If you're concerned about saving a user's password insecurely in a text format to a repository or your server I suggest creating a command to create users for you.

如果您担心以文本格式不安全地将用户密码保存到存储库或您的服务器,我建议您创建一个命令来为您创建用户。

See Laravel docs: https://laravel.com/docs/5.6/artisan#generating-commands

请参阅 Laravel 文档:https://laravel.com/docs/5.6/artisan#generating-commands

In the handle method add something like this:

在 handle 方法中添加如下内容:

public function handle()
{
    $first_name = $this->ask('What is the first name?');
    $last_name = $this->ask('What is the last name?');
    $email = $this->ask('What is the email address?');
    $password = $this->secret('What is the password?');

    AdminUser::create([
        'first_name' => $first_name,
        'last_name' => $last_name,
        'email' => $email,
        'password' => bcrypt($password)
    ]);

    $this->info("User $first_name $last_name was created");
}

You are then able to run the command from the server and you haven't stored anything in a text based format!

然后您就可以从服务器运行该命令,并且您还没有以基于文本的格式存储任何内容!

回答by Selestin Thomas

Using php artisan tinker tool we could add a new user directly to data base.

使用 php artisan tinker 工具,我们可以直接向数据库添加一个新用户。

$user = new App\User();
$user->password = Hash::make('password here ');
$user->email = 'proposed [email protected]';
$user->save();

回答by Marcin Nabia?ek

The most reasonable way is using DatabaseSeeder for such action.

最合理的方法是使用 DatabaseSeeder 进行此类操作。

I'll use example directly from documentation:

我将直接使用文档中的示例:

class DatabaseSeeder extends Seeder {

    public function run()
    {
        $this->call('UserTableSeeder');

        $this->command->info('User table seeded!');
    }

}

class UserTableSeeder extends Seeder {

    public function run()
    {
        DB::table('users')->delete();

        User::create(array('login' => 'admin', 'password' => Hash::make('secret')));
    }
}

After creating such seeder, after php artisan migrateyou can run php artisan db:seedand your 1st user will be created

创建此类播种机后,php artisan migrate您可以运行php artisan db:seed并创建您的第一个用户

Reference: Database seeding in Laravel

参考:Laravel 中的数据库播种

回答by Dhrubo Saha

In Laravel 5.6.39, I am doing following:

在 Laravel 5.6.39 中,我正在执行以下操作:

$user = new App\User();
$user->name = 'dhrubo';       //write whatever name you want
$user->password = Hash::make('dhrubo');    // write the password you want
$user->email = '[email protected]';        // write the email you want
$user->save();