What is Laravel Seeder and how to use seeder in Laravel?

In this blog post, we know about laravel seeder and how to create an id and use it.

Laravel seeder uses to insert multiple rows of data into the database by one command. In this blog post, we learn how to create a Laravel seeder and run a specific seeder class or multiple seeder class by one command.

I suppose you have already created a Laravel Project and connect with your database.

Step: 1 Create a Seeder for Product Table

Run a simple command to create a Seeder for your product table. 

php artisan make:seeder ProductDataSeeder

After running this command you will be found a newly created file in 

database/seeds/ProductDataSeeder.php

<?php
  
use Illuminate\Database\Seeder;
use App\Product;
  
class ProductDataSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
	    	Product::create([
	            'name' => 'sumsumg',
	            'price' => '12000',
	            'discount_price' => '10000',
	        ]);
    }
}

Here, I will insert only three column names, price, and discount_price. if you want to insert multiple columns for the same table you can use the same seeder such as.

public function run(){

   Product::create(['name' => 'Sumsumg','price' => '12000','discount_price' => '10000',]);
   Product::create(['name' => 'LG','price' => '14000','discount_price' => '13000',]);
   Product::create(['name' => 'Motorola','price' => '16000','discount_price' => '15000',]);
   Product::create(['name' => 'MI','price' => '8000','discount_price' => '7000',]);
}

Now we are ready to run above seeder using bellow command:

php artisan db:seed --class=ProductDataSeeder

After running this command check your database.

How to laravel seed multiple records?

You may execute the db:seed Artisan command to seed your database. By default, the db:seed command runs the Database\Seeders\DatabaseSeeder class, which may, in turn, invoke other seed classes. it is used for laravel seed multiple records at a time.

php artisan db:seed

Database\Seeders\DatabaseSeeder

Define all seeder classes in DatabaseSeeder to seed multiple tables at the same time.

/**
 * Run the database seeders.
 *
 * @return void
 */
public function run()
{
    $this->call([
        UserSeeder::class,
        PostSeeder::class,
        CommentSeeder::class,
    ]);
}

I hope it can help you…

Leave a Comment