Mastering Database Seeding in Laravel: A Step-by-Step Tutorial

Database seeding in Laravel is an essential process that facilitates the insertion of dummy or sample data into a database.

The purpose of seeding is to streamline development by eliminating the need to write individual SQL statements for populating database tables. Laravel offers a convenient method to create and maintain seeder files.

One significant advantage of database seeding is the ability to test an application without entering real data. By populating the database with mock information, developers can ensure the proper functioning of their code.

This article pre­sents a step-by-step guide­ on how to create and exe­cute a seed file­ in Laravel 10.

Mastering Database Seeding in Laravel: A Step-by-Step Tutorial


Table of Content

  1. Database Configuration
  2. Create Tables
  3. Create Model
  4. Create Seeding files
  5. Insert data to Tables using Seeder
  6. Run seeders
  7. Output
  8. Conclusion

1. Database Configuration

Open .env file.

Specify the host, database name, username, and password.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=tutorial
DB_USERNAME=root
DB_PASSWORD=

2. Create Tables

Creating 2 tables to insert dummy data using seeder –

  • employees
  • products

employees Table –

  • Create employees table using migration –
php artisan make:migration create_employees_table
  • Now, navigate to database/migrations/ folder from the project root.
  • Find a PHP file that ends with create_employees_table and open it.
  • Define the table structure in the up() method.
public function up()
{
    Schema::create('employees', function (Blueprint $table) {
       $table->bigIncrements('id');
       $table->string('username'); 
       $table->string('name'); 
       $table->string('email');
       $table->string('gender',10);
       $table->smallInteger('status')
       $table->timestamps();
    });
}

products Table –

  • Create products table –
php artisan make:migration create_products_table
  • Now, navigate to database/migrations/ folder from the project root.
  • Find a PHP file that ends with create_products_table and open it.
  • Define the table structure in the up() method.
public function up()
{
    Schema::create('products', function (Blueprint $table) {
       $table->bigIncrements('id');
       $table->string('name');
       $table->text('description');
       $table->integer('quantity');
       $table->smallInteger('status');
       $table->timestamps();
    });
}
  • Run the migration –
php artisan migrate

3. Create Model

Create 2 Models –

  • Employees
  • Products

Employees Model

  • Create Employees Model.
php artisan make:model Employees
  • Open app/Models/Employees.php file.
  • Specify mass assignable Model attributes – username, name, email, gender, and status using the $fillable property.
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Employees extends Model
{
   use HasFactory;

   protected $fillable = [
      'username','name','email','gender','status'
   ];
}

Products Model

  • Create Products Model.
php artisan make:model Products
  • Open app/Models/Products.php file.
  • Specify mass assignable Model attributes – name, description, quantity, and status using the $fillable property.
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Products extends Model
{
   use HasFactory;

   protected $fillable = [
      'name','description','quantity','status'
   ];
}

4. Create Seeding files

To create seeder files use following command –

Syntax –

php artisan make:seeder [Seeder-name]

I am creating 2 seeder files –

  • EmployeesSeeder
php artisan make:seeder EmployeesSeeder
  • ProductsSeeder
php artisan make:seeder ProductsSeeder

Seeder files are created in the database/seeders folder.


5. Insert data to Tables using Seeder

EmployeesSeeder

  • Open database/seeders/EmployeesSeeder.php file.
  • Include Illuminate\Support\Str to generate a random string.
  • Include Illuminate\Support\Arr to pick a random value from Array.
  • Include App\Models\Employees.
  • In run() method write insert code.
  • I am using 2 ways to insert records in the employees table –
    • Predefined values.
    • Generating random values. Using Str to generate random value and assign them to the fields. Similarly, using Arr to pick random value from Array and assign it to the field.
<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;
use Illuminate\Support\Arr;
use App\Models\Employees;

class EmployeesSeeder extends Seeder
{
   /**
   * Run the database seeds.
   *
   * @return void
   */
   public function run()
   {
       // Insert predefined data
       Employees::create([
          'username' => 'yssyogesh',
          'name' => 'Yogesh singh', 
          'email' => 'yogesh@makitweb.com',
          'gender' => 'Male',
          'status' => 1,
       ]);

       // Insert random value in fields
       Employees::create([
          'username' => Str::random(10),
          'name' => Str::random(10), 
          'email' => Str::random(10).'@makitweb.com',
          'gender' => Arr::random(['Male','Female']),
          'status' => 1
       ]);
       Employees::create([
          'username' => Str::random(10),
          'name' => Str::random(10), 
          'email' => Str::random(10).'@makitweb.com',
          'gender' => Arr::random(['Male','Female']),
          'status' => 1
       ]);

   }
}

ProductsSeeder

  • Open database/seeders/ProductsSeeder.php file.
  • Include Illuminate\Support\Str to generate a random string.
  • Include App\Models\Products.
  • Inserting 10 random records in the products table.
<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;
use App\Models\Products ;

class ProductsSeeder extends Seeder
{
    /**
    * Run the database seeds.
    *
    * @return void
    */
    public function run()
    {
        // Insert random 10 records
        for($index=0;$index<10;$index++){
            Products::create([
               'name' => Str::random(10),
               'description' => Str::random(10), 
               'quantity' => rand(10,100),
               'status' => 1
            ]);
        }
    }
}

DatabaseSeeder

  • This is by default Seeder.
  • Using this to execute all seeders.
  • Open database/seeders/DatabaseSeeder.php file.
  • In run() method mention Seeder class in $this->call();.
<?php

namespace Database\Seeders;

// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
    * Seed the application's database.
    *
    * @return void
    */
    public function run()
    {
        $this->call([
            ProductsSeeder::class,
            EmployeesSeeder::class
        ]);

    }
}

6. Run seeders

Run single seeder –

php artisan db:seed --class=EmployeesSeeder

php artisan db:seed --class=ProductsSeeder

Using the above command you need to separately execute seeders one by one.

Run all seeders –

php artisan db:seed

NOTE – Only those seeder execute that are specified in DatabaseSeeder.


7. Output

View Output


8. Conclusion

Laravel’s powerful database seeding feature streamlines the process of database population. Developers can quickly create and insert sample data into the database of their application using Laravel’s built-in seeding system, which is helpful for testing and development.

If you’re a Laravel developer, database seeding is a feature you should definitely explore and use.

In the example, I am using eloquent to insert records but you can also use DB.

If you found this tutorial helpful then don't forget to share.

Leave a Comment