Laravel Database Seeding with Model Factories.

In this article we will cover details on how to Seed your database with test data.

Laravel Database seeding is useful way to populate your database with dummy data which helps you in testing in your Local environment

Before we go into details of laravel database seeding, Let’s first understand the database which you are going to populate.

Assume that you are building an Blog application in Laravel which have common Models like Users, Posts and Comments.

We have generated Model files for each of them along with Migration and the Schema Looks like below.

Users

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('email')->unique();
    $table->timestamp('email_verified_at')->nullable();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

This is the defauly schema of Users table which is provided by Laravel Auth scaffolding

Posts

Schema::create('threads', function (Blueprint $table) {
    $table->increments('id');
    $table->foreign('user_id')
      ->references('id')->on('users')
      ->onDelete('cascade');
    $table->string('title');
    $table->text('body');
    $table->timestamps(); });

For the simplicity of this demonstration our Posts table will have a title, a body and a user_id as a foreign key which reference an id in user table, Since every posts should belong to a user.

Comments

Schema::create('comments', function (Blueprint $table) {
    $table->increments('id');
    $table->foreign('user_id')
      ->references('id')->on('users')
      ->onDelete('cascade');
    $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade'); 
    $table->text('body'); 
    $table->timestamps(); });

Once you are ready with Models and this migration schema, you can create your database by running the following artisan command.

php artisan migrate

Note: If you are looking help with generating Models migration files and generating tables read this tutorial first Create Model with Migration, Controller and generate DB Table

Database Seeding with Model Factories

Now let’s get started with database seeding. We will populate the database tables with Model Factories, Model Factories are located at folder database > factories.

If you have generated the Auth Scaffolding you should already have a file named UserFactory.php in your factories folder with content

$factory->define(App\User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
        'remember_token' => str_random(10),
    ];
});

Factories provide a convenient way to generate new model instances for testing / seeding your application’s database. It makes use of Faker Library to generate arbitrary data for you. For more details on Faker library visit https://github.com/fzaninotto/Faker

Let’s now go ahead and create a new Model Factory for our Posts Model. Navigate to your project root in the terminal / command prompt and run the following command

php artisan make:factory PostFactory --model=Post

This artisan command generates a new Factory file named PostFactory in the factories directory.

Let’s now modify this file, to generate dummy data for columns in Posts table.

$factory->define(App\Post::class, function (Faker $faker) {
    return [
        'user_id' => function(){
            return factory('App\User')->create()->id;
        },
        'title' => $faker->sentence,
        'body'  => $faker->paragraph
    ];
});

For the user_id field we generate a new user and get’s it’s primary key (id), and for title and body we make use of Faker library to generate dummy data.

Similarly, Let’s create a Factory for commments and also modify it.

php artisan make:factory CommentFactory --model=Comment

Let’s now modify this file, to generate dummy data for columns in Comment table.

$factory->define(App\Post::class, function (Faker $faker) {
    return [
        'user_id' => function(){
            return factory('App\User')->create()->id;
        },
        'thread_id' => function(){
            return factory('App\Thread')->create()->id;
        },
        'body' => $faker->paragraph,
    ];
});

We are now ready with our Model factories, To Seed the database open tinker. Go to your terminal and navigate to project root folder and run following command

php artisan tinker

To generate Posts execute following command

$posts = factory('App\Post', 50)->create();

This will create 50 Posts in your database posts table.

To generate comments for posts generate following command

$posts->each(function($post){
factory('App\Comment', 10)->create(['post_id' => $post->id);
});

This will create 10 comments for each posts.

That’s it ! Have fun with Laravel Database seeding and testing.

tgugnani: Web Stuff Enthusiast.