Seeding is very useful while you wanted to keep some dummy data without manual interfere with Database. For example when you deploy you application you insert admin credentials into you users table every time you deploy so that admin user can login. You don't need to to insert those credentials manually every time.
Laravel provides feature of seeding and you can manage your dummy database in your seed classes.
You can create seed like below artisan command:
1
|
php artisan make:seeder UsersTableSeeder
|
1
|
php artisan make:seeder ProductsTableSeeder
|
These command will create a new file 'database/seeds/ProductsTableSeeder.php' and 'database/seeds/UsersTableSeeder.php' which will contain a run() method.
You just need to write insert query inside that run() method like below:
UsersTableSeeder.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
<?php
use Illuminate\Database\Seeder;
class UsersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
\DB::table('users')->insert([[
'name' => 'A',
'email' => 'apple@apple.com',
'password' => bcrypt('123456')
],[
'name' => 'S',
'email' => 'samsung@samsung.com',
'password' => bcrypt('123456')
],[
'name' => 'L',
'email' => 'lg@lg.com',
'password' => bcrypt('123456')
]]);
}
}
|
ProductsTableSeeder.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
<?php
use Illuminate\Database\Seeder;
class ProductsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
\DB::table('products')->insert([[
'productName' => 'A',
'brandName' => 'Apple',
'userId' => 1
],[
'productName' => 'S',
'brandName' => 'Samsung',
'userId' => 2
],[
'productName' => 'L',
'brandName' => 'LG',
'userId' => 3
]]);
}
}
|
Here I'm inserting a list of products into products table.
Now you will require to call this 'ProductsTableSeeder' and 'UsersTableSeeder' class in 'DatabaseSeeder.php' like below code:
1
2
3
4
|
public function run()
{
$this->call([UsersTableSeeder::class,ProductsTableSeeder::class]);
}
|
You are all done with creating seeder.
Now you can run your seeder with below command:
1
|
php artisan db:seed
|
This above command will run your every seeder. You also can manually run a particular seeder like below command:
1
|
php artisan db:seed --class=ProductsTableSeeder
|
You also can migrate and seed the data in one command like:
1
2
|
// Refresh the database and run all database seeds
php artisan migrate:refresh --seed
|
Drop All Tables & Migrate
The migrate:fresh command will drop all tables from the database and then execute the migrate command:
1
|
php artisan migrate:fresh
|
The below command will drop all tables from the database and then execute the migrate command after that will run all the seeders.
1
|
php artisan migrate:fresh --seed
|