How to create database seeder in Laravel

How to create database seeder in Laravel


Here, we will learn how to create seeder for insert multiple records on database table in laravel 5.8. In this, i will show you that, how to create a seeder in laravel, how to use seeder in laravel and how you can use or run a specific seeder in laravel. 

First, in simple lets know What is database seeder in laravel: So Laravel provide us this tool seeder to ADD or INSERT dummy or sample data to our database automatically by laravel command. This is called Database Seeding in Laravel

Step 1: Let's create seeder by following below command:


$ php artisan make:seeder UsersTableDataSeeder


Step 2: After successfull creation of above command seeder, you can see new file created in path : database/seeds/UsersTableDataSeeder.php and now lets put one record to insert by seeder as given below example:

<?php

use App\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;

class UsersTableDataSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
User::create([
'name' => 'User 1',
'email' => 'user@gmail.com',
'password' => Hash::make('user123'),
]);
}
}


 Step 3: Now, let's Seed the data into database using following command.


$ php artisan db:seed --class=UsersTableDataSeeder

Now your data is successfully seeded into your database in laravel by the above Laravel artisan Command.

Step 4: If you have multiple Database Seeder like, UserTableDataSeeder, SettingTableSeeder and BlogTableSeeder, so at that time we can't follow Step 3 command to seed the data, so you need to add this Seeder or Database Seeder in the file path: "database/seeds/DatabaseSeeder.php". and paste as per your requirement. Eg give below:


<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
$this->call(UsersTableDataSeeder::class);
$this->call(SettingTableSeeder::class);
}
}


Step 5: Now, run the below artisan command to seed all the data at once into your database


$ php artisan db:seed

Now your all data will be seeded successfully.

© Copyright - 2018 - 2021 | All rights reserved at Funda of Web IT