How to create database seeder in laravel 6 ?

Laravel 6 , Laravel

Nicesnippets

3015

21-09-2019


hi guys,

In this article,we will learn to create seeder with insert record into database in laravel 6.

Laravel 6 includes a simple method of seeding your database with test data using seed classes. All seed classes are stored in the database/seeds directory.

In this tutorial, I will let you know what is database seeder, what is the use of database seeder and how to generate seeder file with migrations in Laravel 5.

In this example, I will seed some test/dummy data into users table that will not created by any users.

For testing any applications where you will need different user's credentials to test all the scenarios, then you can populate the data by using seed functionality provided by Laravel.

You can generate the seeder class by running following command :

php artisan make:seeder UsersTableSeeder

Once above command will be executed successfully then you will get "UsersTableSeeder" class in database/seeds directory, All the seeders class generated with artisan command will be place in the database/seeds directory.

There will be only one method in seeder class by default :run.

Within the run method, I will write the insert query to load some user data into users table.

Ok, let's open the "UsersTableSeeder.php" file and add the following line of code to insert user data :

UsersTableSeeder

<?php

use Illuminate\Database\Seeder;

class UsersTableSeeder extends Seeder

{

/**

* Run the database seeds.

*

* @return void

*/

public function run()

{

DB::table('users')->insert([

'name' => str_random(6),

'email' => strtolower(str_random(6)).'@gmail.com',

'password' => bcrypt('test@123')

]);

}

}

The above code will insert one record at a time, If you need to insert in bulk then put the code into a loop.

Now run the following command to seed the data :

php artisan db:seed --class=UsersTableSeeder

When you run the artisan command with db:seed option without specifying any class, then this will run the DatabaseSeeder class.

You can break seeders into multiple files and call them in default "DatabaseSeeder" class by using call method. call method is used to call additional seed class.

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder

{

/**

* Run the database seeds.

*

* @return void

*/

public function run()

{

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

}

}

It will help you...


Recommended Posts