Database Seeders

Let's create a Knowledgebase Application

In this video lesson we will learn how to use a database seeder to add fake data into our database. This will give us something to work with early on in our building phase.

Video Information

Hi everyone, welcome back to Laracademy it's Mickey again and in this lesson we are going to create the database seeders to help us make our database models and relationships.

Let's dive right in by opening up our terminal and creating our seeder.

php artisan make:seeder CategoryTableSeeder
php artisan make:seeder ArticleTableSeeder

Now the reason we are making two seeders is because we do not have our models setup yet, or our relationships. So we currently are not going to be using those relationships to help us seed. This is something we can come back and do but for now let's just create our seeds using the database methods; we will return to this and fix it up. Open up database/seeds/CategoryTableSeeder.php.

Now we know our categories need to have a name, so we can easily use Faker to accomplish this. And we also want to add in a couple of them, so say 10 categories.

use Faker\Generator as Faker;

public function run(Faker $faker)
{
  foreach(range(1, 10) as $number) {
    DB::table('categories')->insert([
      'name' => $faker->words(rand(1, 5), true),
    ]);
  }
}

Now we can run this seeder by doing the following in the console

php artisan db:seed --class=CategoryTableSeeder

We can verify that we have some records by loading up tinker

php artisan tinker

And checking the database.

DB::table('categories')->get();

Now let's get some articles. Load up ArticleTableSeeder.php

use Faker\Generator as Faker;

public function run(Faker $faker)
{
  foreach(range(1, 10) as $number) {
    // select a random category
    $category = DB::table('categories')->inRandomOrder()->first();

    // insert into articles
    $id = DB::table('articles')->insertGetId([
        'title' => $faker->words(rand(1, 10), true),
        'content' => $faker->realText(rand(200, 300)),
    ]);

    // link
    DB::table('article_category')->insert([
        'category_id' => $category->id,
        'article_id' => $id,
    ]);
  }
}

Now we can run this seeder from the terminal.

php artisan db:seed --class=ArticleTableSeeder

And let's check it in the terminal.

\DB::table('articles')->get()

The final thing we can do is add these seeders to the default database seeder. Open up DatabseSeeder.php and add the following under run.

$this->call(CategoryTableSeeder::class);
$this->call(ArticleTableSeeder::class);

Now that our database seeders are completed, we are ready to move on to the database models and relationships.

Do you have a question? Go ahead and ask it below.

Please login to ask your question