In the past when we were doing database data testing, it is generally manual to add data, such as in the database query using SQL statements for data insertion. If the data is low, it's pretty easy, but if the data is too big, it's going to hurt, even if you copy the SQL statement. But all this, in Laravel, has become very easy.
Examples of this article are tested for the latest version 5.3 of Laravel, please leave a comment in the comments section if there is a problem with the other version. Create a table
For a friend who likes to command line, Laravel's artisan command is simply not convenient.
For information on artisan, you can refer to:
English Document: Https://laravel.com/docs/5.3/artisan
Chinese document: Https://laravel-china.org/docs/5.3/artisan start
Command: PHP artisan make:migration create_users_table
Meaning: Create a table named users.
Then you can find a file similar to 2014_10_12_000000_create_users_table.php in the Database/migrations directory.
As with previous PHP statements, we can write the fields and constraints in the 2014_10_12_000000_create_users_table.php file where we want to create the table.
<?php use
Illuminate\support\facades\schema;
Use Illuminate\database\schema\blueprint;
Use illuminate\database\migrations\migration;
Class Createuserstable extends migration
{
/**
* Run the migrations.
*
* @return void */public
function up ()
{
schema::create (' Users ', function (Blueprint $table) {
$table->increments (' id ');
$table->string (' name ');
$table->string (' email ')->unique ();
$table->string (' password ');
$table->remembertoken ();
$table->timestamps ();}
);
/**
* Reverse the migrations.
*
* @return void */public
function down ()
{
Schema::d ropifexists (' users ');
}
A migration class contains two methods up and down.
The up contains the details of creating a table.
Down and the former are the opposite.
Schema::create accepts two parameters. The first is the name of the table you want to create; the second is a closure (anonymous function) that gets the Blueprint object that defines the new table.
For more information on migration, refer to: https://laravel.com/docs/5.3/migrations#migration-structure Common column name type control
command |
description |
$table->incremen TS (' id '); |
database primary key self-increasing ID |
$table->integer (' votes '); |
equivalent to the INTEGER type in the database |
$table->float (' Amount '); |
equivalent to FLOAT type in database |
$table->char (' name ', 4); |
equivalent to the CHAR type in the database |
$table->string (' name '); |
equivalent to VARCHAR in the database |
$table->datetime (' created_at '); |
equivalent to the DATETIME type in the database |
$table->enum (' Choices ', [' foo ', ' Bar ']); |
equivalent to the ENUM type in the database |
$table->tinyinteger (' numbers '); |
equivalent to the TINYINT type in the database |
$table->timestamps (); |
add created_at and updated_at columns |
For more information about column name types, refer to the following: Https://laravel.com/docs/5.3/migrations#creating-columns Some of the constraint conditions of column names
Schema::table (' Users ', function ($table) {
$table->integer (' votes ')->unsigned (); Unsigned type
});
Modifying Device |
Description |
->first () |
Place the column as the first column in the table (for MySQL only) |
->after (' column ') |
Place the column after another column (for MySQL only) |
->nullable () |
Allow the value of this column to be NULL |
->default ($value) |
Specify default values for columns |
->unsigned () |
Set integer column UNSIGNED |
generating tables in the database
Build command: PHP artisan migrate
Rollback command: PHP artisan migrate:rollback populate test data (emphasis) method One
Let's modify the Databaseseeder class that comes with the Laravel installation and add a database insert statement to the Run method:
We can find databaseseeder.php this file in the Database/seeders directory.
<?php use
illuminate\database\seeder;
Class Databaseseeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void */public
function run ()
{
db::table (' users ')->insert ([
' name ' => Str_random,
' email ' => str_random (10). ' @gmail. com ',
' password ' => bcrypt (' secret '),
];
}
Then execute the command: PHP artisan db:seed
Now you can go to the database to view, you will find that a new piece of data
There is a problem here, if we have more tables in the late period, then the single filler class will not become extremely large. A solution is provided in Laravel, and we can create additional fillers specifically for a single table.
Command: PHP artisan make:seeder Usertableseeder
Meaning: Create a seed class named users or a class that is understood as a fill test. Usertableseeder This name can be arbitrarily taken, but better to distinguish. All the frame-generated fillers are located in the Database/seeders directory.
<?php use
illuminate\database\seeder;
Class Userstableseeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void */public
function run ()
{
db::table (' users ')->insert ([
' name ' => Str_random,
' email ' => str_random (10). ' @gmail. com ',
' password ' => bcrypt (' secret '),
];
}
In the Databaseseeder class, you can use the call method to perform additional padding classes, using the call method to allow you to decompose the database population into multiple files.
<?php use
illuminate\database\seeder;
Class Databaseseeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void */public
function run ()
{
$this->call (userstableseeder::class);
}
}
As in the previous steps, follow the command: PHP artisan db:seed
Now you can go to the database to view, you will find a new data method two
Method one and we used to insert a data in the SQL statement is the same effect, so there is not much ascension. What we want to do is fill in multiple test data at once, so we can use method two.
Manually specifying the properties for each model fill is cumbersome and cumbersome, and in laravel we can use model factories to easily generate a large number of database records.
First, look at the Model factory documentation to learn how to define the factory, and after defining the factory, you can use the Help function factory to insert records into the database. Model Factory
As a start, let's take a look at the database/factories/modelfactory.php file, which contains a factory definition:
<?php
/**
* Run database fill
* @return void
/
$factory->define (app\user::class, function (faker\ Generator $faker) {
static $password;
return [
' name ' => $faker->name,
' email ' => $faker->unique ()->safeemail,
' password ' = > $password: $password = Bcrypt (' secret '),
' Remember_token ' => str_random (a),
];
In the closure, as a factory definition, we return the default test values for all properties on the model. The closure receives faker instances of the PHP library, allowing you to easily generate multiple types of random data for the test.
Here to note the Faker instance, you can refer to the Https://github.com/fzaninotto/Faker
This faker instance provides a lot of available random data, such as we're going to populate the names, use $faker->name, and it will eventually generate Prof. Such data as King Feil. This is undoubtedly very convenient and can be highly simulated.
more information about the model factory can be referred to:
English Document: Https://laravel.com/docs/5.3/database-testing#model-factories
Chinese documents: Https://laravel-china.org/docs/5.3/database-testing#model-factories using Help functions Factory
<?php use
illuminate\database\seeder;
Class Userstableseeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void */public
function run ()
{
factory (App\user::class,)->create ([' Password ' => bcrypt (' 123456 ')];
}
Where factory accepts two parameters: one is the eloquent model, and the other is the number of inserted data. The statement in the Run method above represents the creation of 50 models and saves them to the database.
And then let's go back to databaseseeder.php call method is used to generate test data.
Execute command: PHP artisan db:seed
Now you can go to the database to see, you will find 50 new data.