Home  >  Article  >  PHP Framework  >  How to quickly implement data filling in laravel (using seeder)

How to quickly implement data filling in laravel (using seeder)

藏色散人
藏色散人forward
2021-11-03 15:55:493486browse

The following tutorial column of Laravel will introduce you to laravel's use of seeder to fill data in the data table. I hope it will be helpful to everyone!

laravel uses seeder to fill data in the data table

I will show you how to quickly fill the data in the data table

First of all When executing the php artisan command, various command instructions will appear. Find

php artisan make:seeder

and create the corresponding file according to the command instructions, as shown below

php artisan make:seeder TestSeeder

First I create a test table, as shown below

##The content of the TestSeeder.php file is as follows

<?php

use Illuminate\Database\Seeder;

class TestSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table(&#39;test&#39;)->insert([
            &#39;name&#39; => str_random(10),
            &#39;sex&#39; => rand(1,2), // 1男 2女
            &#39;email&#39; => str_random(10).&#39;@qq.com&#39;,
            &#39;password&#39; => bcrypt(&#39;123456&#39;), // bcrypt为hash加密
        ]);
    }
}

Execute the following command to fill in fake data

php artisan db:seed --class=TestSeeder


Execute one side each time you add one command, this will be very troublesome. It is better to write a for loop to newly insert

for ($x=0; $x<=10; $x++) {
     DB::table(&#39;test&#39;)->insert([
          &#39;name&#39; => str_random(10),
          &#39;sex&#39; => rand(1,2), // 1男 2女
          &#39;email&#39; => str_random(10).&#39;@qq.com&#39;,
          &#39;password&#39; => bcrypt(&#39;123456&#39;), // bcrypt为hash加密
     ]);
}

. The data in the database is displayed as follows:

If you need to add test data for multiple tables at the same time, you need to add in DatabaseSeeder.php:

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    public function run()
    {
        // $this->call(UsersTableSeeder::class);
         $this->call(CreateDepartmentsSeeder::class);
         $this->call(CreateUsersSeeder::class);
         $this->call(CreateWagesSeeder::class);
    }
}

Execute the following command to fill in the test data for multiple tables

php artisan db:seed
rrree

Official document address: https://laravel.com/docs/5.5/seeding#writing-seeders

The above is the detailed content of How to quickly implement data filling in laravel (using seeder). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete