seeding data in laravel

How to use Laravel Seeders?

Seeders are php classes that allow us to fill the database with some records so we can test our software.

laravel makes it easy for us to do that we just need to create seeders and run them.

How to Create a Seeder in Laravel

to create a seeder in laravel first you need to run make:seeder artisan command followed by a name for the seeder:

php artisan make:seeder ProductSeeder

a ProductSeeder.php class will be created in app\database\seeders. in this class, we write our code in the run method to create records for “products” table in database.

I will create fake products here.

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class ProductSeeder extends Seeder
{

    public function run()
    {
        DB::table('products')->insert([

            [
                'title' => 'Mac Book Pro',
                'price' => 1300,
                'inventory' => 10,
                'discount_percent' => 5,
            ],
            [
                'title' => 'iPhone 15 Pro',
                'price' => 999,
                'inventory' => 55,
                'discount_percent' => 0,
            ],
        ]);


    }
}

we used DB Facade to insert records in the database.

we also can use Eloquent like this:



class ProductSeeder extends Seeder
{

    public function run()
    {
      $productItems = [

            [
                'title' => 'Mac Book Pro',
                'price' => 1300,
                'inventory' => 10,
                'discount_percent' => 5,
            ],
            [
                'title' => 'iPhone 15 Pro',
                'price' => 999,
                'inventory' => 55,
                'discount_percent' => 0,
            ],
        ];

        foreach ($productItems as $item){

            $product = Product::create($item);

        }

    }
}

then we have to run the seeder.

we can call the seeder in the run method of DatabaseSeeder.php

   public function run()
    {
        $this->call([
            ProductSeeder::class
        ]);
    }

then we have to run:

php artisan db:seed

this will create the records.

we also can put all of the seeders we created in the run method and run them all at once.

    public function run()
    {
        $this->call([
            ProductSeeder::class,
            PostSeeder::class,
            UserSeeder::class,
        ]);
    }

Using Factories to Create Fake Database Records

if you want to have 50 or 100 or even 1000 records seeded in a table you cannot just write every record manually.

in this situation you have to use model factories. model factories are php classes that help us create data for records in a table.

to create a model factory for “products” table, run:

php artisan make:factory ProductFactory

there will be a ProductFactory.php in app\dataase\factories.

in the definition method, we have to define how every column is created.

for this, we can use the Faker package which is installed in Laravel by default. we also can create our own logic for that.

class ProductFactory extends Factory
{
 
    public function definition()
    {
        return [
            'title' => $this->faker->word,
            'price' => random_int(1, 1000),
            'discount_percent' => random_int(1, 100),
            'inventory' => random_int(0, 500),
        ];
    }
}

in the definition method, we return an array that defines every column of the table.

here for the title, we use Faker to generate a title. price, discount_percent, and inventory will be created by the random_int function.

now that we created the product factory we can use it inside the seeder to generate the records:

//ProductSeeder.php

use App\Models\Product;

class ProductSeeder extends Seeder
{

    public function run()
    {
             Product::factory()->count(20)->create();
    }
}

this will create 20 records in the products table.

fake products generate by Product Factory in Laravel

using factories we can create relationship records too. for example, if every product has related comments we can create them.

public function run()
{
      Product::factory()->count(20)->hasCooments(10)->create();
}

before running this seeder make sure that the relationship and the seeder for the Comment model are set up correctly.

//Product Model
//Product.php 
public function comments(){
   return $this->hasMany(Comment::class);
}
//CommentFactory.php 
 public function definition()
    {
        return [
            'author' => $this->faker->name,
            'comment' => $this->faker->text,
        ];
    }

Running a specific seeder

instead of seeding all the tables, you can run a specific seeder too.

php artisan db:seed --class=ProductSeeder

Seeding Data in Migration Files

in a project, you might want to have default data in the database so you won’t need to run seeders every time.

you can write the seeder code in a migration file. this way whenever you run the migration seeding will be done too.

the code should be in the up() method:

   //products migration file

use Illuminate\Support\Facades\DB;

    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->decimal('price');
            $table->integer('discount_percent')->default(0);
            $table->integer('inventory');
            $table->timestamps();
        });

//seed data after the table is created.
        DB::table('products')->insert([

            [
                'title' => 'Mac Book Pro',
                'price' => 1300,
                'inventory' => 10,
                'discount_percent' => 5,
            ],
            [
                'title' => 'iPhone 15 Pro',
                'price' => 999,
                'inventory' => 55,
                'discount_percent' => 0,
            ],
        ]);

    }

this is very useful when we want to have default users and config settings.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *