Tự học Laravel: (13) SEEDING AND FACTORY

In Laravel, it is possible to embed initial data in a DB using the artisan db:seed command. You can create initial data required for the system, and create sample data to be used in development. This time, I will create sample data to be used in development in the Articles table.

SEEDER FILE CREATION

First, create a Seeder file with the artisan command.

php artisan make:seeder ArticlesTableSeeder

Seeder files are created under the database/seeds directory.
By default, the DatabaseSeeder.php file already exists.

database
└── seeds
    ├── ArticlesTableSeeder.php
    └── DatabaseSeeder.php

DATABASESEEDER.PHP

Modify DatabaseSeeder.php as follows:

<?php //database/seeds/DatabaseSeeder.php
 
use Illuminate\Database\Seeder;
 
class DatabaseSeeder extends Seeder
{
    public function run()
    {
        $this->call([
            ArticlesTableSeeder::class, // ①
            // OtherTableSeeder::class, // ②
        ]);
    }
}
  1. Add a call to ArticlesTableSeeder.
  2. Add it here if you want to call multiple Seeders.

ARTICLESTABLESEEDER.PHP

Modify ArticlesTableSeeder.php as follows:

<?php //database/seeds/ArticlesTableSeeder.php
 
use Illuminate\Database\Seeder;
 
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;
use Carbon\Carbon;
use App\Article;
 
class ArticlesTableSeeder extends Seeder
{
    public function run()
    {
        DB::table('articles')->delete(); // ①
 
        $faker = Faker::create('en_US'); // ②
 
        for ($i = 0; $i < 10; $i++) {    // ③
            Article::create([
                'title' => $faker->sentence(),
                'body' => $faker->paragraph(),
                'published_at' => Carbon::today()
            ]);
        }
    }
}
  1. Use Query Builder to delete all the records in the Articles table. 
  2. I am creating dummy data using Faker . Laravel comes standard with Faker. 
  3. Create 10 Article data.

By the way, field assignment of mass assignment is disabled during Seeding .

RUN SEED

php artisan db:seed Seeded:ArticlesTableSeeder 

Use tinker to check the results.

$ php artisan tinker
>>> App\Article::all()->toArray();
=> [
       [
           "id"           => "1",
           "Title" => "pleasure avoided thanks offices do not provide for free."
           "Body" => "In order to be smart and that no resilience. There is often a great experience of how to pay. So welcome to welcome the intense pain. No pain, or other wise."
           "created_at"   => "2015-02-24 17:35:48",
           "updated_at"   => "2015-02-24 17:35:48",
           "published_at" => "2015-02-24 17:35:48"
       ],
...

Data has been registered.

FACTORY

In Seeder, try to rewrite dummy data in the Articles table using Laravel’s Factory function.

First, create a Factory file.

php artisan make:factory ArticleFactory

Factory files are created under the database/factories directory.
By default the UserFactory.php file already exists.

database
└── factories
    ├── ArticleFactory.php
    └── UserFactory.php

ARTICLEFACTORY.PHP

Modify ArticleFactory.php as follows:

<?php //database/factories/ArticleFactory.php
 
use Faker\Generator as Faker;
use Carbon\Carbon;
 
$factory->define(App\Article::class, function (Faker $faker) { // ①
    return [ // ②
        'title' => $faker->sentence(),
        'body' => $faker->paragraph(),
        'published_at' => Carbon::today(),
    ];
});
  1. Change what was Model::class to App\Article::class
  2. Define the items and contents to be set. Create dummy data using Faker.

ARTICLESTABLESEEDER.PHP

Modify ArticlesTableSeeder.php to use the factory() function.

<?php //database/seeds/ArticlesTableSeeder.php
 
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
 
class ArticlesTableSeeder extends Seeder
{
    public function run()
    {
        DB::table('articles')->delete();
 
        factory(App\Article::class, 20)->create(); // ①
    }
}
  1. Create data in DB by specifying the class name and the number of models to be created in the factory() function.

RUN SEED

php artisan db:seed
Seeded: ArticlesTableSeeder

Use tinker to check the results.

php artisan tinker

>>> App\Article::count()
=> 20
>>> 

Twenty data can be registered.

TRY USING FACTORY WITH TINKER

The factory can also be run from tinker. You can easily generate dummy data any time by defining factory.

php artisan tinker

>>> App\Article::count()
=> 20
>>> DB::table('articles')->delete()
=> 20
>>> App\Article::count()
=> 0

>>> $articles = factory(App\Article::class, 2)->make()
=> Illuminate\Database\Eloquent\Collection {#2893
     all: [
       App\Article {#2889
         Title: "Explicabo the incident snacks thanks to attain called hate."
         body: "blandishments pleasure is sufficient. That needs careful or the like. pleasures regular than happy to carry the undesirable task."
         published_at: "2018-08-25 00:00:00",
       },
       ...
     ],
   }
>>> App\Article::count()
=> 0
>>> $articles->count()
=> 2

>>> $articles = factory(App\Article::class, 3)->create()
=> Illuminate\Database\Eloquent\Collection {#2886
     all: [
       App\Article {#2874
         Title: "And even when it is but a headache."
         body: "And it is easy for the pain and suffering the consequences. It is our pain, but were told that they encounter a choice. How the body is wise little pleasures. Asperiores resilience, but the pleasure of doing things."
         published_at: "2018-08-25 00:00:00",
         updated_at: "2018-08-25 20:39:51",
         created_at: "2018-08-25 20:39:51",
         id: 87,
       },
       ...
     ],
   }
>>> App\Article::count()
=> 3
>>> $articles->count()
=> 3
>>> 

After first checking the number of data in the Articles table in the DB, we delete it once.

Next, I use factory(…)->make(). Although the number of data in DB has not increased, the number of $ articles set in the return value of the make() function is two.

Finally, I use factory(…)->create(). The number of data in DB is increasing, and the number of $articles is three.

Did you understand the difference between make() and create()? create() creates data in DB. Make() only returns the generated data, DB does nothing.

If you only create temporary test data, you should use tinker and factory instead of using Seeder.

Seeder is used to generate the initial data needed for the system, and test data seems to be well-divided to use the factory.

SUMMARY

You can now do the following:

  • Create data to DB using Seeder
  • Create Test Data Using Factory

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.