Laravel db:seedder

Vckin發表於2020-04-20

1, 建立填充檔案

    php artisan make:seeder UserTableSeeder

2, 在run方法裡面填充資料程式碼

use Illuminate\Database\Seeder;
use App\Models\User;

class UserTableSeeder extends Seeder
{

    public function run()
    {

        $users = factory(User::class)->times(50)->make();
        User::insert($users->makeVisible(['password', 'remember_token'])->toArray());
        $user = User::find(1);
        $user->name = 'admin';
        $user->email = 'admin@admin.com';
        $user->password = md5('flxt123password');
        $user->save();
    }
}

3,在DatabaseSeeder裡面呼叫 UserTableSeeder

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
  public function run()
 {
     $this->call(UsersTableSeeder::class);
 }
 }

4,在UserFactory.php裡面

use App\Models\User;
use Faker\Generator as Faker;
use Illuminate\Support\Str;


$factory->define(User::class, function (Faker $faker) {
    $date_time = $faker->date . ' ' . $faker->time;
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'email_verified_at' => now(),
        'password' => md5('flxt123'.$faker->password),
        'remember_token' => Str::random(10),
        'created_at' => $date_time,
        'updated_at' => $date_time
    ];
});

5, 執行 php artisan db:seed –class=UserTableSeeder

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章