Tutorialsplane

Laravel Database Seeding


Laravel Database Seeding – The Laravel Database Seeding is used to test data seed classes.


Laravel Database Seeding.

Let us understand how to use laravel Database Seeding.

Function:-

There are some followings function available in laravel Database Seeding.

1. Introduction.

Laravel includes a simple method of seeding your database with test data using seed classes. Seed classes are stored in the database/seeds directory. Seed classes can have any name you want, but probably should follow some sensible convention, such as UsersTableSeeder.

2. Writing Seeders.

To generate a seeder, execute the make:seeder Artisan command. All seeders generated by the framework will be placed in the database/seeds directory.

php artisan make:seeder UsersTableSeeder

A seeder class only contains one method by default run. This method is called when the
db:seed Artisan command is execute. Within the run command you can insert data into your browser however you want.

Let’s look at a simple example.

<?php use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class DatabaseSeeder extends Seeder
{
    public function run()
    {
        DB::table('users')-?>insert([
            'name' => str_random(10),
            'email' => str_random(10).'@gmail.com',
            'password' => bcrypt('secret'),
        ]);
    }
}

Using Model Factories

To generate large amount of database records we can use model factories. Once you have defined your factories, you can use the factory helper function to insert records into your database.

Let’s look at a simple example.

public function run()
{
    factory(App\User::class, 50)->create()->each(function ($u) {
        $u->posts()->save(factory(App\Post::class)->make());
    });
}

Calling Additional Seeders

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

Let’s look at a simple example.

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

3. Running Seeders.

Once you have written your seeder classes, you can use the db:seed Artisan command to seed your database. The db:seed command runs the DatabaseSeeder class, which can be used to called other seed classes.

php artisan db:seed

php artisan db:seed --class=UsersTableSeeder

You can also seed your database using the migrate:refresh command, which will also rollback and re-run all of your migrations.

php artisan migrate:refresh --seed

Laravel Tutorial