PHP framework "Laravel" # 5 Create test data using seeding function and Faker

PHP framework “Laravel” # 5 Create test data using seeding function and Faker

You can significantly reduce the time spent preparing the database, so please use it when developing web applications with Laravel.

table of contents

What is Laravel’s seeding function? Creating a Cedar File 2.1 Creating a File 2.2 How to Write a Cedar File Executing seeding 3.1 Execute a single seeder file 3.2 Execute multiple seeder files at once 3.3 Initialize the database and execute the seeder file Faker library 4.1 How to use Faker library 4.2 Dummy data that can be generated by Faker library Finally

1. What is Laravel’s seeding function?

Seeding is a word that means “sowing” or “rice planting” in English, and is likened to pouring initial data or test data into a database.The initial data is registered from the beginning when operating the Web application, such as master information that links names such as prefecture names and department names with code values ​​used in the system, login information of administrator users, etc. Is the prerequisite data.Test data is data prepared for operation check and test, and is dummy data that is different from the production data. These data must be re-registered each time the database is initialized.Especially when performing a test, it is necessary to replace the test data for each test item, so the database initialization and test data registration are repeated frequently.Laravel’s seeding feature can reduce the time it takes to do this.By creating a seeder file that describes the contents of the initial data and test data and executing the Artisan command, the data according to the contents will be registered in the database. In other words, once you create a seeder file, you can reproduce the initial data and test data on the database just by executing the command.Similar to the migration function that creates a table based on the migration file, it is possible to operate the database without using SQL, so it is recommended for those who are not good at SQL.In the next section, we will explain in detail how to create a seeder file, which is a “design document” when executing the seeding function of Laravel.

2. Creating a seeder file

2.1 Creating a file

The seeder file can be automatically generated based on the template prepared from the beginning by executing the Artisan make: seeder command.First, go to the Laravel project (PROJECT_NAME) and execute the following command.#Move to Laravel project (PROJECT_NAME) cd ~ / html / laravel / PROJECT_NAME~ / html / laravel / PROJECT_NAME #Generate a seeder file for admin users #Generate php-7.1 artisan make: seeder AdminUserSeeder- 7.1 Artisan Make : Seeder AdminUserSeeder #Generate a seeder file for test users #Generate php-7.1 artisan make: seeder TestUserSeeder- 7.1 Artisan Make : Seeder TestUserSeeder This time, we will create a seeder that registers initial data for the User table for user management that exists as standard in Laravel.Use the Artisan make: seeder command to generate an AdminUserSeeder file that registers an administrator user and a TestUserSeeder file that registers a test user.If successful, a seeder file will be created directly under database / seeds /.

2.2 How to write a seeder file

Since the seeder file generated in 2.1 is empty with no processing written, describe the contents of the initial data you want to register in the database in each file.First, open the AdminUserSeeder file for administrative user registration with a text editor and edit it.database / seeds / AdminUserSeeder.php<? php php use Illuminate \ Database \ Seeder; Illuminate \ Database \ Seeder ; use App \ User; App \ User ; class AdminUserSeeder extends Seeder { / ** * Run the database seeds. * * @Return void * / public function run () { // 1st admin user User :: create ([ ‘name’ =>’administrator ABC’, ’email’ =>’abc@example.com’, ‘password’ => Hash :: make (‘test1234’), ]); // Second admin user User :: create ([ ‘name’ =>’admin DEF’, ’email’ =>’def@example.com’, ‘password’ => Hash :: make (‘test1234’) , ]); } }AdminUserSeeder extends Seeder / ** public function run () { // 1st admin user User :: create ([[ ‘name’ => ‘Administrator ABC’ , ’email’ => ‘abc@example.com’ , ‘password’ => Hash :: make ( ‘test1234’ ), ]); // Second admin user User :: create ([[ ‘name’ => ‘Administrator DEF’ , ’email’ => ‘def@example.com’ , ‘password’ => Hash :: make ( ‘test1234’ ), ]); } This time, register users named “Administrator ABC” and “Administrator DEF”.* Since it is an operation on the User table, you can use the model class (User.php) that already exists, but if you want to add data to your own table, you need to create the model class in advance.In the argument of the User :: create procedure, the values ​​are set for the keys “name”, “email”, and “password” in the associative array, and these keys correspond to the column names of the table.In other words, the values ​​set in the array of keys called “name” (“Administrator ABC” and “Administrator DEF”) are inserted in the “name” column of the User table.Next, open the TestUserSeeder file for test user registration with a text editor and edit it.database / seeds / TestUserSeeder.php<? php php use Illuminate \ Database \ Seeder; Illuminate \ Database \ Seeder ; use App \ User; App \ User ; class TestUserSeeder extends Seeder { / ** * Run the database seeds. * * @Return void * / public function run () { // 100 test users Register for ($ cnt = 1; $ cnt <= 100; $ cnt ++) { User :: create ([ ‘name’ =>’test user’. $ Cnt, ’email’ =>’test’. $ Cnt. ‘@ example.com’, ‘password’ => Hash :: make (‘testtest’), ]); } } }TestUserSeeder extends Seeder / ** public function run () { // Register 100 test users for ( $ cnt = 1 ; $ cnt <= 100 ; $ cnt ++ ) { User :: create ([[ ‘name’ => ‘test user’ . $ Cnt , ’email’ => ‘test’ . $ Cnt . ‘@ Example.com’ , ‘password’ => Hash :: make ( ‘testtest’ ), ]); } } Since the test data requires a lot of data, we use a loop to register 100 users in the User table. In this way, the ability to use loops and conditional branches is one of the merits of using a seeder file.After creating the seeder file, reconfigure the autoload so that Laravel will recognize the created seeder file.php-7.1 ../composer.phar dump-autoload- 7.1 ../ Composer . Phar Dump – Autoload Laravel uses a mechanism called composer autoloading that automatically loads the necessary files. As you proceed with development with Laravel, the error “Class <file name> does not exist” may occur in various situations such as when a new file is added. If you get the above error, try reconfiguring the autoload first.

3. Performing seeding

The seeder file created in step 2 is used for seeding using the Artisan command. There are multiple ways to perform seeding with the Artisan command, so here are some typical ones.

3.1 Execute the seeder file alone

If you want to register data in a table that has already been created, use the Artisan db: seed command.php-7.1 artisan db: seed –class = AdminUserSeeder- 7.1 Artisan Db : Seed – Class = AdminUserSeeder Specify the class name of the seeder file you want to execute in the option –class. (Note that it is not a file name)If the message Database seeding completed successfully. Is output, it is successful.Make sure that the administrator user data has been added to the database.

Administrator user data

3.2 Execute multiple seeder files at once

With the 3.1 method, you can only execute one seeder file per command.It’s okay if the number of seeder files is small, but as the number increases, it’s a bit inconvenient because you have to execute as many commands as there are files each time you initialize the database.If you use DatabaseSeeder.php which exists in database / seeds from the beginning, you can execute multiple seeder files at once, so I will show you how to do it.First, before executing the command, add the information of the seeder file created this time to DatabaseSeeder.php.database / seeds / DatabaseSeeder.php<? php php use Illuminate \ Database \ Seeder; Illuminate \ Database \ Seeder ; class DatabaseSeeder extends Seeder DatabaseSeeder extends Seeder { / ** / ** * Seed the application’s database. * * @Return void * / public function run () public function run () { { $ this-> call ([ -> call ([[ AdminUserSeeder :: class, AdminUserSeeder :: class , TestUserSeeder :: class TestUserSeeder :: class ]); ]); } } } Just add the seeder file you want to use to the array of arguments for $ this-> call as above. Now you are ready to run multiple seeder files.After editing DatabaseSeeder.php, initialize the database with the Artisan migrate: refresh command, and then perform seeding again with the Artisan db: seed command.php-7.1 artisan migrate: refresh – 7.1 Artisan Migrate : Refresh php-7.1 artisan db: seed- 7.1 Artisan Db : Seed In 3.1, the class name of the seeder file was specified as an option, but it is not necessary to specify the class name when executing seeding based on DatabaseSeeder.Make sure that the administrator user data and the test user data are added to the database.

Test user

3.3 Initialize the database and run the seeder file

In the previous section, we introduced how to execute multiple seeder files at once using Database Seeder. Not only that, you can also combine the steps of initializing the database and then seeding into a single command.php-7.1 artisan migrate: refresh –seed- 7.1 Artisan Migrate : Refresh – Seed If you specify –seed as an option for the Artisan migrate: refresh command, Database Seeder seeding is automatically performed after database initialization.When you actually start development and testing, this command has more opportunities to use, so please remember and use it.

4. Faker library

Faker, a PHP library for automatically generating dummy data, is installed as standard in Laravel. This time, I will show you how to use it to save time in creating dummy data for troublesome tests.

4.1 How to use Faker library

Let’s change the test user data created in 2.2 using the Faker library to more realistic data.database / seeds / TestUserSeeder.php<? php php use Illuminate \ Database \ Seeder; Illuminate \ Database \ Seeder ; use App \ User; App \ User ; class TestUserSeeder extends Seeder { / ** * Run the database seeds. * * @Return void * / public function run () { // 100 test users Register for ($ cnt = 1; $ cnt <= 100; $ cnt ++) { $ faker = Faker \ Factory :: create (‘ja_JP’); User :: create ([ ‘name’ => $ faker-> lastName .”’. $ Faker-> firstName, ’email’ => $ faker-> email, ‘password’ => Hash :: make (‘testtest’), ]); } } }TestUserSeeder extends Seeder / ** public function run () { // Register 100 test users for ( $ cnt = 1 ; $ cnt <= 100 ; $ cnt ++ ) { = Faker \ Factory :: create ( ‘ja_JP’ );User :: create ([[ ‘name’ => $ faker- > lastName . ”’ . $ Faker- > firstName , ’email’ => $ faker- > email , ‘password’ => Hash :: make ( ‘testtest’ ), ]); } } With Laravel, you can automatically generate various dummy data just by calling the Factory :: create procedure. This time, we will use dummy data of last name (lastName), first name (firstName), and email address (email).Dummy data is stored in the return value $ faker of the Factory :: create procedure, so get the value from each corresponding field.After editing the seeder file, initialize the database and perform seeding.php-7.1 artisan migrate: refresh –seed- 7.1 Artisan Migrate : Refresh – Seed Make sure that the test user’s name and email address registered in the database is a dummy that is closer to the real data.

Dummy close to real data

4.2 Dummy data that can be generated by Faker library There are many dummy data that can be generated by the Faker library besides names and email addresses. Below are some of the most frequently used ones.Name (Kana) $ faker-> lastKanaName, // Last name Kana $ faker-> firstKanaName, // Name KanaUser ID $ faker-> userName-> userName phone number $ faker-> phoneNumber-> phoneNumber Postal code $ faker-> postcode-> postcode Street address $ faker-> address-> address Prefectures $ faker-> prefecture-> prefecture Municipalities $ faker-> city-> city Town / street address $ faker-> streetAddress-> streetAddress Building name, room number $ faker-> secondaryAddress-> secondaryAddress company name $ faker-> company-> company Random numbers $ faker-> numberBetween (1, 100)-> numberBetween ( 1 , 100 ) Random text (number of characters) $ faker-> realText (100)-> realText ( 100 )

5. Finally

This time, I introduced the seeding function of Laravel. If you use it together with the previous migration function, you will be able to change the database under development very quickly. Also, in the test, by creating a seeder file for each test case, the test environment can be reproduced immediately. Please take advantage of Laravel’s seeding function, which has only merit like this.