Laravel Database Seeding Using faker And ModelFactories to generate Seeds


Example

1) BASIC SIMPLE WAY

Database-driven applications often need data pre-seeded into the system for testing and demo purposes.

To make such data, first create the seeder class

ProductTableSeeder

use Faker\Factory as Faker;
use App\Product;

class ProductTableSeeder extends DatabaseSeeder {

public function run()
{
    $faker = $this->getFaker();

    for ($i = 0; $i < 10; $i++)
    {
        $name =         $faker->word;
        $image =        $faker->imageUrl;
       
        Modelname::create([
            'name' => $name,
            'image' => $image,
        ]);
      }
    }
 }

To call a be able to execute a seeder class, you have call it from the DatabaseSeeder class, Simply by passing the name of the seeder you wish to run:

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder {

    protected $faker;

    public function getFaker() {
        if (empty($this->faker)) {
            $faker = Faker\Factory::create();
            $faker->addProvider(new Faker\Provider\Base($faker));
            $faker->addProvider(new Faker\Provider\Lorem($faker));
        }
        return $this->faker = $faker;
    }
    public function run() {
        $this->call(ProductTableSeeder::class);
    }
}

Do not forget to run $ composer dump-autoload after you create the Seeder, since they are not automatically autoloaded by composer (unless you created seeder by artisan command $ php artisan make:seeder Name)

Now you are ready to seed by running this artisan command php artisan db:seed

2) USING Model Factories

First of all you to define a default set of attributes for each Model in App/database/factories/ModelFactory.php

Taking a User model as an exemple, This how a ModelFactory looks like

$factory->define(App\User::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->email,
        'password' => bcrypt(str_random(10)),
        'remember_token' => str_random(10),
    ];
});

Now Create a table seeder php artisan make:seeder UsersTableSeeder

And add this

public function run()
{
    factory(App\User::class, 100)->create()
}

then add this to the DatabaseSeeder

public function run()
{
    $this->call(UsersTableSeeder::class);
}

This will seed the table with 100 records.