Saturday, September 9, 2017

Seeding database in Laravel

Using php artisan make:seeder
=========================

php artisan make:seeder PeopleTableSeeder
inside PeopleTableSeeder class

<?php

use Illuminate\Database\Seeder;
use Faker\Factory as Faker;
use Carbon\Carbon;

class PeopleTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
      $faker = Faker::create();
      DB::table('people')->insert(
          [
            'first_name' => $faker->firstname,
            'last_name' => $faker->lastname,
            'age' => rand(10, 44),
            'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
            'updated_at' => Carbon::now()->format('Y-m-d H:i:s')
          ]
        );
    }
}

In DatabaseSeeder class

$this->call(PeopleTableSeeder::class);


For multiple entry
======================
 DB::table('people')->insert([
   [], []
 ]);

Using PHP factory
====================
$factory->define(App\Person::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->name,
        'first_name' => $faker->firstname,
        'last_name' => $faker->lastname,
        'age' => rand(10, 44)
    ];
});

In DatabaseSeeder class

factory(Person::class, 100000)->create();

css snippet for blogger code highlighting

code, .code {     display: block;     background: beige;     padding: 10px;     margin: 8px 15px; }