4
2

More than 1 year has passed since last update.

laravel Factoryを用いてテストデータを作成する(追記編)

Last updated at Posted at 2022-07-24

概要

  • Factoryを用いてデータを作成する複数の方法をまとめる。

1件のデータを作成する

  • 下記の記載で1レコードのデータを登録する事ができる。

    モデルクラス::factory()->createOne();
    
  • Factoryによって作成されたデータのモデルが返される。

    $eloquent = モデルクラス::factory()->createOne();
    
  • 下記のように記載することで特定の情報を固定してレコードを作成する事ができる。

    モデルクラス::factory()->createOne([
        'カラム名' => 特定のデータ,
    ]);
    
  • ちなみにcreate()関数を用いて1レコードを作成することもできる。この場合戻り値がコレクションで返される。

    $collection = モデルクラス::factory()->count(1)->create();
    
  • createOne()create()関数の実装部分にPHPDocでレスポンスの記載がされている。

    • createOne()

      vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php
      /**
       * Create a single model and persist it to the database.
       *
       * @param  (callable(array<string, mixed>): array<string, mixed>)|array<string, mixed>  $attributes
       * @return \Illuminate\Database\Eloquent\Model|TModel
       */
      public function createOne($attributes = [])
      {
          return $this->count(null)->create($attributes);
      }
      
    • create()

      vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php
      /**
       * Create a collection of models and persist them to the database.
       *
       * @param  (callable(array<string, mixed>): array<string, mixed>)|array<string, mixed>  $attributes
       * @param  \Illuminate\Database\Eloquent\Model|null  $parent
       * @return \Illuminate\Database\Eloquent\Collection<int, \Illuminate\Database\Eloquent\Model|TModel>|\Illuminate\Database\Eloquent\Model|TModel
       */
      public function create($attributes = [], ?Model $parent = null)
      {
          if (! empty($attributes)) {
              return $this->state($attributes)->create([], $parent);
          }
      
          $results = $this->make($attributes, $parent);
      
          if ($results instanceof Model) {
              $this->store(collect([$results]));
          
              $this->callAfterCreating(collect([$results]), $parent);
          } else {
              $this->store($results);
          
              $this->callAfterCreating($results, $parent);
          }
      
          return $results;
      }
      

レコード数を指定してテストデータを作成する

モデルクラス::factory()->count(レコード数)->create();

テーブルに値を格納せずモデルクラスのみを作成する

$model = モデルクラス::factory()->count(レコード数)->make();

特定の情報だけは指定してレコードに情報を登録する

  • 下記の様にcreateOneの引数に配列でキー名と指定したい情報を記載してレコードを作成することも可能である。(例えばユーザー情報を1レコード作成する時にemailカラムの値はtest@example.comでpasswordカラムの値はp@ssw0rdという文字列がハッシュ化された物を指定する場合)

    $this->user = User::factory()->createOne([
        'email' => 'test@example.com',
        'password' => Hash::make('p@ssw0rd')
     ]);
    

参考文献

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