Laravel Seeder-用种子播客用我自己选择的电子邮件创建2个用户

时间:2019-03-22 12:03:30

标签: laravel

这是默认情况下用户工厂中的内容

$factory->define(User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'email_verified_at' => now(),
        'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
        'remember_token' => Str::random(10),
    ];
});

我想创建2个用户,让他们在播种机中说这些电子邮件地址。

user1's email = abc@abc.com
user2's email = xyz@xyz.com

我需要在其中放置代码的地方。在播种机或工厂中,情况如何?

2 个答案:

答案 0 :(得分:3)

如果您只想创建2封电子邮件,则可以将其放入播种机中,那里不需要工厂,可以这样写:-

首先创建播种器:-

php artisan make:seeder UserTableSeeder

这将为您创建以下代码,然后您可以在其中添加数据:-

<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class UserTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
    App\User::create([
    'name' => 'name',
    'email' => 'abc@abc.com',
    'email_verified_at' => now(),
    'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
    'remember_token' => Str::random(10),
    ]);

         App\User::create([
    'name' => 'another name',
    'email' => 'xyz@xyz.com',
    'email_verified_at' => now(),
    'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
    'remember_token' => Str::random(10),
    ]);
    }
}

然后您可以使用以下命令运行播种机:-

php artisan db:seed --class=UserTableSeeder 

但是如果您想创建多个用户,则可以使用model factories

答案 1 :(得分:0)

在您的DatabaseSeeder.php中,将以下代码添加到run()函数中:

    DB::table('users')->insert([

        ['id'=>'1', 'user'=>'User1', 'email'=>'abc@abc.com', 'email_verified_at' =>now(),
         'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'created_at' => now(), 'updated_at' => now()],

        ['id'=>'2', 'user'=>'User2', 'email'=>'xyz@xyz.com', 'email_verified_at' =>now(),
         'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'created_at' => now(), 'updated_at' => now() ],

    ]);