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:49 3361browse

The following tutorial column ofLaravelwill 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

insert([ 'name' => str_random(10), 'sex' => rand(1,2), // 1男 2女 'email' => str_random(10).'@qq.com', 'password' => bcrypt('123456'), // 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('test')->insert([ 'name' => str_random(10), 'sex' => rand(1,2), // 1男 2女 'email' => str_random(10).'@qq.com', 'password' => bcrypt('123456'), // 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:

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