0
0

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 1 year has passed since last update.

LaravelのSeederとFactoryを使ったテストデータ生成

Last updated at Posted at 2024-02-04

はじめに

テストや初期データの設定には、LaravelのSeederとFactoryが非常に便利です。この記事では、SeederとFactoryの基本的な使い方と、それらを使ってテストデータを効率よく生成する方法について紹介します。

Seederの基本

Seederを使用すると、データベースにテストデータを挿入できます。これは開発プロセスの初期段階で非常に便利です。

Seederの作成

php artisan make:seeder UsersTableSeeder

上記コマンドで、database/seedsディレクトリに新しいSeederクラスが作成されます。

Seederの実装

Seederクラス内のrunメソッドを使用して、データベースにデータを挿入します。

public function run()
{
    DB::table('users')->insert([
        'name' => 'John Doe',
        'email' => 'johndoe@example.com',
        'password' => bcrypt('password'),
    ]);
}

Seederの実行

php artisan db:seed --class=UsersTableSeeder

特定のSeederを実行する場合は、上記のコマンドを使用します。

Factoryの基本

Factoryは、テストデータを生成するためのテンプレートを提供します。特に大量のデータを簡単に生成する際に便利です。

php artisan make:factory UserFactory --model=User

database/factoriesディレクトリに新しいFactoryクラスが作成されます。

Factoryの実装

Factoryクラスでは、定義メソッドを使用して、モデルのデフォルト値を設定します。

public function definition()
{
    return [
        'name' => $this->faker->name,
        'email' => $this->faker->unique()->safeEmail,
        'password' => bcrypt('password'),
    ];
}

Factoryを使用したデータの生成

Seeder内でFactoryを利用すると、大量のテストデータを簡単に生成できます。

public function run()
{
    User::factory()->count(50)->create();
}

まとめ

SeederとFactoryは、Laravelでテストデータを生成する際に非常に強力なツールです。適切に使用することで、開発プロセスを効率化し、テストの精度を高めることができます。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?