Laravel Faker產生假資料使用中文

主要是看到FB Laravel 社團中有人分享Faker 產生中文方法,但是是寫在AppServiceProvider內,其實還有其他方式

首先還是建立Model做測試

php artisan make:model post -m

設定該migrations post database table

public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');               //文章標題
            $table->text('body');                  //文章內容
            $table->unsignedInteger('user_id');    //文章發起人
            $table->timestamps();
        });
    }

建立與table對應的PostFactory.php 於database/factories下

<?php
use Faker\Generator as Faker;
$factory->define(App\Post::class, function (Faker $faker) {
    return [
        'title'   => $faker->title(10),
        'body'    => $faker->realText(200),
        'user_id' => factory(\App\User::class)->create()->id
    ];
});
?>

最後在config\app.php下新增一行,指定Faker 使用zh_TW語言

'faker_locale' => 'zh_TW',

測試

php artisan tinker
factory(App\Post::class)->make()