8 min read

Database seeding is a process of filling data tables with fake data. Developers use this process for testing purposes. Laravel offers a facility to fill data tables with test data using seeder classes. All seeder classes are stored in the database/seeds directory. By default, a DatabaseSeeder class is defined for you. You can run other seeder classes with the call() method of this default class. Here is an explanation of how you can do that, so let’s get started. 

Step 1:

To create a seeder: 

php artisan make:seeder UserSeeder 

This command will create one file UserSeeder.php in the seeds folder. All seed classes are stored in the database/seeds directory.

Step 2:

Write code in the UserSeeder.php file.

<?php use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; use Illuminate\Support\Facades\Hash; class UserTableSeeder extends Seeder{   /**     * Run the database seeds.     *     * @return void     */    public function run(){       DB::table(‘user’)->insert([            ‘name’      => ‘Admin’,            ’email’     => ’[email protected]’,            ‘status’    => ‘active’,            ‘password’  => Hash::make(‘12345678’),        ]);    }}

There are two ways to run this seeder class:

Way 1: Run a single seeder 

If you want to run only one seeder class, execute this command: 

php artisan db:seed –class=UserSeeder

Way 2: Run all seeder

To run all seeder classes, you have to declare your seeder in the DatabaseSeeder class file.

Open database/seeds/DatabaseSeeder.php

And write code to declare seeder classes:

<?php   use Illuminate\Database\Seeder;   class DatabaseSeeder extends Seeder{   /**     * Seed the application’s database.     *     * @return void     */    public function run()    {       $this->call(UserTableSeeder::class);        ….   ….    }}

Then execute the following command to run all listed seeders:

php artisan db:seed 

Conclusion

Apart from laravel, the database seeding functionality has been featured in many PHP frameworks. It shows how important this concept is for web developers. There might be different ways to fill test data in the data tables, faker library is one such way. Do you want to us make a tutorial on the faker library too? Let us know in the comment section below.

If you are looking for a software firm to create your business website or mobile app, your search ends here. We build affordable and robust software solutions for businesses to digitally thrive on. Contact us to get a quote. You can mail us at [email protected] or WhatsApp us on +91 95 37 84 38 39.

"Have WordPress project in mind?

Explore our work and and get in touch to make it happen!"