[IntermediateLaravel] 9-Database-Seeding-and-Model-Factories

Source: Internet
Author: User
[IntermediateLaravel] 9-Database-Seeding-and-Model-Factories

Generally, when setting up an application, we need to insert some simple data. what should we do? the conclusion is to run the Database-Seeding function.

Database-Seeding data filling

By default, database \ seeds \ only has a single DatabaseSeeder. php. we create the UsersTableSeeder. php class:

Class UsersTableSeeder extends Seeder {/*** Run the database seeds. ** @ return void */public function run () {// You can also use App \ User: create () or DB: table () without using factory () other factory ('app \ user', 50)-> create ();}}

Modify DatabaseSeeder. php:

Class DatabaseSeeder extends Seeder {/*** Run the database seeds. ** @ return void */public function run () {Model: unguard (); // call UsersTableSeeder $ this-> call ('userstableseeder ');}}

Run the db: seed command: php artisan db: seed. then we can query whether data is inserted:

  • In Unix systems, run the following command: sqlite3 storage/database. sqlite select * from users;
  • In Windows, you can download the free version of Database4, and open the storage/database. sqlite directory file for viewing:

Here, you will certainly ask these personal names How the mailbox names are automatically generated. Next let's look at them.

Data rules

ModelFactory. php in the database \ factories directory defines the rule for inserting data in the User table:

$factory->define(App\User::class, function (Faker\Generator $faker) {  return [    'name'          => $faker->name,    'email'          => $faker->email,    'password'      => bcrypt(str_random(10)),    'remember_token' => str_random(10),  ];}); 

You can rewrite the rules in UsersTableSeeder:

Class UsersTableSeeder extends Seeder {/*** Run the database seeds. ** @ return void */public function run () {// rewrite the rules in Model Factories and insert John Doe's name factory ('app \ user', 50) -> create (['name' => 'John Doe ']);}

The result is as follows:

We can delete invalid data before inserting data:

Class DatabaseSeeder extends Seeder {protected $ toTruncate = ['users'];/*** Run the database seeds. ** @ return void */public function run () {Model: unguard (); // cyclically delete a table foreach ($ this-> toTruncateas $ table) {DB :: table ($ table)-> truncate ();} $ this-> call ('userstableseeder ');}}

Create a LessonSeeder

This time we will create both Model and Factories and run the command line:

Php artisan make: model Lesson -- migration

Complete the attribute fields in CreateLessonsTable:

class CreateLessonsTable extends Migration{  /**   * Run the migrations.   *   * @return void   */  public function up()  {    Schema::create('lessons', function (Blueprint $table) {      $table->increments('id');      $table->string('title');      $table->text('body');      $table->timestamp('published_at');      $table->timestamps();    });  }   /**   * Reverse the migrations.   *   * @return void   */  public function down()  {    Schema::drop('lessons');  }} 

Run the command line: php artisan migrate to create the lessons table structure.

Complete the call of LessonsTableSeeder in DatabaseSeeder

Class DatabaseSeeder extends Seeder {protected $ toTruncate = ['users'];/*** Run the database seeds. ** @ return void */public function run () {Model: unguard (); // cyclically delete a table foreach ($ this-> toTruncateas $ table) {DB :: table ($ table)-> truncate () ;}$ this-> call ('userstableseeder'); $ this-> call ('lesonstableseeder ');}}

If you execute the command line php artisan db: seed, an exception occurs:

The reason is that only the database is loaded in composer. json by default.

There are two solutions:

1. run the command line: composer dump-autoload

2. use the command line to create Seeder: php artisan make: seeder LessonsTableSeeder

Insert data

Add Lesson data insertion rules in ModelFactory. php:

$factory->define(App\Lesson::class, function (Faker\Generator $faker) {  return [    'title'          => $faker->sentence,    'body'            => $faker->paragraph,    'published_at'    => $faker->dateTime()  ];}); 

Execute the command line: php artisan db: seed, OK. The data is inserted smoothly, for example:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.