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
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('test')->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:
<?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
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!