LoginSignup
1
2

More than 5 years have passed since last update.

[Laravel] seederでデータベースにテストデータを入れる

Posted at

概要

今回は1つのusersテーブルを作ります。

users
id
name
text

こんな感じ。これをseederを使ってテストデータを入れていきます。

マイグレーション

データベースを作成します。

php artisan make:migration create_users_table --create=users

諸々の設定。データベースにnameとtextのカラムを追加。

create_users_table.php
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name', 50);
            $table->text('text');
            $table->timestamps();
        });
    }

migrateする。

php artisan migrate

モデル作成

次にテーブルに紐付くモデルを作る

php artisan make:model User

モデルで、いじれるカラムの設定。

User.php
class User extends Model
{
    protected $fillable = [
        'name',
        'text',
    ];
}

ファクトリーとシーダー

ここでファクトリーを使います。使わなくてもいいのかも。
とりあえずモデルに紐付くファクトリーファイル作る。

php artisan make:factory UserFactory --model=User

どこのカラムにどんなテストデータを入れるかの設定。

UserFactory.php
$factory->define(App\User::class, function (Faker $faker) {
    return [
        'name' => 'exampleName',
        'text' => 'exampleText',
    ];
});

ファクトリーができたらシーダーを作る。

php artisan make:seeder UsersTableSeeder

ファクトリーで定義されたUserモデルを50個作成。

UsersTableSeeder.php
    public function run()
    {
        factory(User::class, 50)->create();
    }

DatabaseSeederでコールしてあげる。

DatebaseSeeder.php
    public function run()
    {
        $this->call(UsersTableSeeder::class);
    }

ここまでできたら最後にartisanコマンド。

php artisan db:seed

エラーが出たら下記のコマンドしてみるといいかも。

composer dump-autoload

php artisan db:seed

確認

Sequel Proで確認して見ます。

image.png

image.png

いけてるっぽい!!

まとめ

seederでテストデータの投入方法を見ました。
まだまだ勉強中です、、

1
2
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
1
2