Home > PHP Framework > Laravel > body text

Introduction to laravel's method of using Faker data filling (code)

不言
Release: 2019-04-12 10:02:01
forward
4080 people have browsed it

The content of this article is about the introduction (code) of laravel's method of using Faker data filling. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Introduction: When doing development, adding test data is essential. Laravel has built-in very convenient data filling. The following is an example.

Data migration

Create data model and data migration firstphp artisan make:model Models/FakerUser -m

Create only a few A simple field, edit database/migrations/{now_date}_create_faker_users_table.php file

/**
     * Run the migrations.
     *
     * @return void
     */7
    public function up()
    {
        Schema::create('faker_users', function (Blueprint $table) {
            $table->increments('id');
            $table->char('name', 20)->comment('姓名');
            $table->string('email', 50)->comment('邮箱');
            $table->tinyInteger('age')->comment('年龄');
            $table->char('city', 20)->comment('城市');
            $table->timestamps();
        });

        DB::statement("ALTER TABLE `faker_users` comment'测试用户表'"); // 表注释
    }
Copy after login

Run data migrationphp artisan migrate After that, the data table is created.

Data filling

Create data filling filephp artisan make:seeder FakerUsersSeeder

Create After completion, we can manually add several pieces of test data in the run() method. But a good way is to use Model Factory, and then turn your attention to the model factory;

Create model factoryphp artisan make:factory FakerUsersFactory;

In the model factory, you can generate test data through Faker\Generator, edit database/factories/FakerUsersFactory.php

<?php use Faker\Generator as Faker;

$factory->define(\App\Models\FakerUser::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->safeEmail,
        'age' => $faker->numberBetween(8, 80),// 数字在 8-80 之间随机
        'city' => $faker->city,
        'created_at' => $faker->dateTimeBetween('-3 year', '-1 year'),// 时间在 三年到一年 之间
        'updated_at' => $faker->dateTimeBetween('-1 year', '-5 month'),// 时间在 一年到五个月之间
    ];
});
Copy after login

The function of Faker\Generator can be clearly seen from the above code. There are many data types it can generate. For more types, you can read the official documentation. Although it is in English, it has examples and is easy to understand;

Faker The data generated is by default It is in English, you can set faker_locale to zh_CN in config/app.php;

model factory is written, the next step is transfer. Returning to the data filling file database/seeds/FakerUsersSeeder.php, in the run() method the following code

/**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(\App\Models\FakerUser::class)->times(1000)->make()->each(function ($model) {
            // 数据入库
            $model->save();
        });
    }
Copy after login

time() is generated times, the make() method is to create a model instance, and in the each() method, the generated model instance is stored in the database.

The last step is to perform data filling. After composer dump-autoload php artisan db:seed --class=FakerUsersSeeder

Test

Okay, let’s see if the database data is generated correct. Look at the total

Introduction to laravels method of using Faker data filling (code)

There is no problem with the total number, and the random data

Introduction to laravels method of using Faker data filling (code)

is also correct. of

The above is the detailed content of Introduction to laravel's method of using Faker data filling (code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!