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 3 years have passed since last update.

Laravelでモデルのファクトリーを作成

Last updated at Posted at 2020-03-08

#はじめに
備忘録になります。
Laravel5.5系で実施。

#仕様
LaravelでUserモデルのファクトリーを作成したい
・name:ランダムな名前
・email:重複しないメールアドレス
・password:複数レコードを作成する際は同じパスワードを使用。
・remember_token:10桁のランダム値

#コマンド
php artisan make factory UserFactory --model=User
今回は、Seederでfactoryを呼び出すためSeederも追加。
php artisan make:seeder UsersTableSeeder

#factoryソースコード

UserFactory.php
<?php

use Faker\Generator as Faker;

$factory->define(App\User::class, function (Faker $faker) {
    static $password;

    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => $password ?: $password = bcrypt('test1234'),
        'remember_token' => str_random(10),
    ];
});

fakerを作る際はこちらが参考になりました。
[Laravel5.1]Fakerチートシート

#Seederソースコード

UsersTableSeeder.php
<?php

use Illuminate\Database\Seeder;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\User::class, 50)->create();
    }
}

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?