Using Factories to seed your database with Laravel

I have recently explored factories for seeding my database. Previously I looked at seeding a database in a way which is very simple but necessary for my needs.  I also needed some dummy data on bulk to save a little time so I have used a factory to do this.

So I needed to add some dummy data to a table but I needed it to follow some specific rules.  This is what I did.

Open database\factories\ModelFactory.php

$factory->define(App\FrameworkOutcome::class, function (Faker\Generator $faker) {
    return [
        'framework_id' => rand(1,3),
        'category_id' => rand(1,5),
        'outcome' => $faker->sentence(10),
        'order' => 0,
        'active' => 0,
        'created_at' => date('Y-m-d H:i:s'),
        'updated_at' =>  date('Y-m-d H:i:s')
    ];

});

There is a factory for users already set up and ready to go.  It is pretty self explanatory but I will expand a little on what I did.  If you want you can skip down to where I add in the call within the DatabaseSeeder.php to get it to run.

In the code above and for your needs you can override any details you want by passing an array for your table contents.

The FrameworkOutcome model I am working with relates to two other tables Framework and Categories.  Suffice it to say that I have populated these tables but to make my outcomes relevant to these other tables I have had to specify certain attributes such as 'framework_id' needs an integer of 1, 2 or 3.  I used rand(1,3) to achieve this and the same for ‘category_id’.

I used $faker->sentence with 10 words in the sentence. There are a bunch of faker formatters which can be found on the Github page.

Now once this is all set up, go to database\seeds\DatabaseSeeder.php and add the following line in the ‘run’ method.

factory(FrameworkOutcome::class, 20)->create();

Run the seeder: php artisan db:seed

Twenty records with random data within the specified guidleines will be added to the database.

Leave a Reply

Your email address will not be published. Required fields are marked *