【Laravel】Factoryをダミーデータを手軽に投入する

やりたい事

LaravelにあるFactoryを使ってテスト用にダミーデータを手軽、かつ大量に作りたい。

今回はtitleやbodyに適当に値入れたpostデータを10個手軽に作リマス。

Factory使用前のpostテーブル Image from Gyazo

Factory使用後のpostテーブル(ダミーデータ10個)

Image from Gyazo

Factoryとは

LaravelにはseederというデータをDBに挿入する仕組みがあり、これとmigrationを使ってDBに初期値を入れるのが一般的です。 今回はLaravelのFactoryという機能を使ってダミーデータの定義を作り、seederにてデータを作っていきます。

公式

いざ実践

大まかな流れは以下です。

  1. postテーブルを作成
  2. Factoryを作成
  3. seederファイルにてFactoryを利用
  4. atrisanコマンドでデータ挿入

1.postテーブルを作る

postテーブルはmigrationファイルに定義を書いて作っていきます。

まずはartisanコマンドでmigrationファイルを “php artisan make:migration create_<テーブル名>_table`

作ったらそこにテーブル定義を書く。


<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
    /// テーブル定義
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->mediumText('body');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

かけたら php artisan migrate

で反映させる。

2.Factoryを作成

テーブル定義ができたらFactoryを作っていきます。 この際にモデルも作っていきましょう。

php artisan make:model "Post" --factory

これでmodelとfactoryが作成されます。 Image from Gyazo

Image from Gyazo

factoryの中身を記述していきます。 今回はtitle、bodyに適当な値を入れたダミーデータを作ります。

<?php

namespace Database\Factories;

use App\Models\Post;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class PostFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = \App\Models\Post::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
     
     
  //ここにダミーデータの情報を記述
    public function definition()
    {
        return [
            'title' => $this->faker->title(), //fakerを使うと適当な値が生成される
            'body' => $this->faker->paragraph(),
            'created_at' => now(),

        ];
    }
}

3.seederファイルにてFactoryを利用

Factoryを作ったので、これをseederに記述して大量にデータを生成します。

database/seeder/DatabaseSeeder.php にfactoryを利用してデータを生成する

\App\Models\Post::factory(10)->create(); を記述します。

Image from Gyazo これはPostFactoryを利用して10個分ダミーデータを生成するという意味で、10を変更してダミーデータの数を調整できます。

4. atrisanコマンドでデータ挿入

最後は

php artisan db:seed

DBにダミーデータが入ります。 Image from Gyazo 完成。

Select the fields to be shown. Others will be hidden. Drag and drop to rearrange the order.
  • Image
  • SKU
  • Rating
  • Price
  • Stock
  • Availability
  • Add to cart
  • Description
  • Content
  • Weight
  • Dimensions
  • Additional information
  • Attributes
  • Custom attributes
  • Custom fields
Click outside to hide the compare bar
Compare
Compare ×
Let's Compare! Continue shopping