16
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravel で開発用ユーザーとテストユーザーを Seeder で作成する方法

Posted at

やること

  • 実際にログインできる開発用ユーザー 1 つと、テストユーザーを 20 程作成する

ModelFactory

database/factories/ModelFactory.php

<?php

$factory->define(App\User::class, function (Faker\Generator $faker) {
    static $password;

    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => $password ?: $password = bcrypt('secret'),
        'remember_token' => str_random(10),
    ];
});

UsersTableSeeder

database/seeds/UsersTableSeeder.php

<?php

use Illuminate\Database\Seeder;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // 開発用ユーザーを定義
        App\User::create([
            'name' => 'develop_user',
            'email' => 'my_email@gmail.com',
            'password' => Hash::make('my_secure_password'), // この場合、「my_secure_password」でログインできる
            'remember_token' => str_random(10),
        ]);

        // モデルファクトリーで定義したテストユーザーを 20 作成
        factory(App\User::class, 20)->create();
    }
}

DatabaseSeeder.php

database/seeds/DatabaseSeeder.php

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // UserTableSeeder を呼び出すよう登録
        $this->call(UsersTableSeeder::class);
    }
}

実行コマンド


※ seeder すべて実行
$ php artisan db:seed

※ seeder のクラスを指定して実行
$ php artisan db:seed --class=UsersTableSeeder

※ データベースをリセットして seeder すべて実行
$ php artisan migrate:refresh --seed

検証環境


$ php -v
PHP 5.6.8 (cli) (built: Apr 15 2015 15:07:09)
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies
    with Xdebug v2.2.5, Copyright (c) 2002-2014, by Derick Rethans



$ cat composer.json | grep laravel/framework
        "laravel/framework": "5.3.*",

所感

  • seeder 実行は基本的に php artisan migrate:refresh --seed でやったほうがデータベースを清潔に保てていい感じ。
  • 消したらまずいデータがある場合には使わないように注意

EOF

16
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?