学習備忘録

よく忘れてしまうのをここにメモしておく

factoryでオリジナルの値を生成したいする方法

課題

  • facoryのチートシートに求める値が存在していないので自身で実装しなければいけない

対処法

  • factory内でランダムに値を生成する場合
<?php
$factory->define(UserProfile::class, function (Faker $faker) {
    $residence = ['東京都', '大阪府', '静岡県', '福岡県', '神奈川県', '沖縄県', '北海道', '香川県'];
    $job = ['エンジニア', 'CA', '商社', '銀行員', '公務員', '国家公務員', '医師', 'パイロット'];
    $text = [
        'こんばんわ☺️
        
        仲良くしていただけると嬉しいです❗️',
        '初めまして☺️
        
        マッチングアプリは初めてですが是非よろしくお願いします。',
        'こんにちわ☺️
        
        真剣に出会いを探しています。連絡取れると嬉しいです❗️',
    ];

    return [
        'user_id' => function() {
            return factory(App\User::class)->create()->id;
        },
        'user_name' => null,
        'residence' => $residence[rand(0, 7)],
        'age'       => rand(20, 30),
        'height'    => rand(160, 180),
        'job'       => $job[rand(0,7)],
        'img_url'   => null,
        'text'      => $text[rand(0, 2)],

    ];
});
  • 順序通りにfactoryを生成したい場合
<?

private $img_url = [
        'https://matching-kou.s3-ap-northeast-1.amazonaws.com/3/40e84e95.jpg',
        'https://matching-kou.s3-ap-northeast-1.amazonaws.com/4/42905757_1946147315443146_8509928890392442925_n.jpg',
        'https://matching-kou.s3-ap-northeast-1.amazonaws.com/5/a0001508_main.jpg',
        'https://matching-kou.s3-ap-northeast-1.amazonaws.com/6/aru.jpg',
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null
    ];
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $this->call(UserTableSeeder::class);
        $this->call(UserProfileTableSeeder::class);

        for($i = 3; $i < 23; $i++) {
            factory(App\User::class, 1)->create(['id' => $i, 'sex' => 1, 'name' => $this->user_name[$i - 3]])->each(function ($user) use($i){
                factory(App\Model\UserProfile::class, 1)->create(['user_id' => $user->id, 'user_name' => $this->user_name[$i - 3], 'img_url' => $this->img_url[$i - 3]]);
            });
        }

        for($i = 23; $i < 43; $i++) {
            factory(App\User::class, 1)->create(['id' => $i, 'sex' => 0, 'name' => $this->user_name[$i - 1]])->each(function ($user) use($i){
                factory(App\Model\UserProfile::class, 1)->create(['user_id' => $user->id,'user_name' => $this->user_name[$i -1], 'img_url' => $this->img_url[$i - 1]]);
            });
        }

        $this->call(RoomsTableSeeder::class);
        $this->call(LikesTableSeeder::class);
        $this->call(MessagesTableSeeder::class);
    }