Database: Seeding

To create fake data inside the Database, you can use seeding. All seed classes are stored in the database/seeds directory.

To generate a seeder

php artisan make:seeder UserSeeder

Writing Factories

To get started, take a look at the database/factories/UserFactory.php file in your application.

<?php

use Faker\Generator as Faker;

$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),
    ];
});

$factory->define(App\Test::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'user_id' => rand(1,100),                
    ];
});

Using Model Factories

<?php

use Illuminate\Database\Seeder;

class TestSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\Test::class, 10)->create();
    }
}

<?php

use Illuminate\Database\Seeder;

class UserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\User::class, 10)->create();
    }
}

Calling Additional Seeders

Within the DatabaseSeeder class, you may use the call method to execute additional seed classes.

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //$this->call(TestSeeder::class);
        //$this->call(UserSeeder::class);
        $this->call([
        	TestSeeder::class,
        	UserSeeder::class
        ]);       
    }
}

Running Seeders


php artisan db:seed

or 

php artisan db:seed --class=UserSeeder

Once you have written your seeder, you may need to regenerate Composer’s autoloader using the dump-autoload command:

composer dump-autoload
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s