Laravel 10 Database Seeder Tutorial Example

Last Updated on by in Laravel
In general, this tutorial shed light on the foundational and most asked topic in laravel domain, which is database seeders in laravel. No wonder we will write a detailed memoir, in the form of Laravel Database Seeder.We have been getting our audience request consecutively and respectively For laravel seeder example tutorial for many days. Now, with your consensus, let’s understand the concept of laravel seeder generator with example.

Why the need arise to propel database seeder topic in laravel tutorial? Hmm, theoretically, when we develop web applications in laravel, we need to test multiple data. In the development process, adding real data is a bit difficult. This is what Database Seeder set out to do. It generates fake or dummy data for you and incorporate the data in the database table.

With it, you can simultaneously create a single seeder or multiple seeders. You can test your laravel app with the data, which seems real to some extent.

This tutorial creates excellent opportunities and answers the following questions spontaneously:

  • What is database seeder in laravel
  • How to create seeder in laravel
  • Why we should use database seeder in laravel

Not to worry, i will try to answer all the above questions in this tutorial from the best of my capability.

Laravel Database Seeder Example

Let’s comprehend what laravel officially says about Database Seeder.

Laravel adds a simple process for database seeding with test data. Other, seeders classes are kept inside the database/seeds folder.

Generically, you may name it anything you want, but generic names sound more sense. Such as EmployeeSeeder, etc, It comes with the DatabaseSeeder class, which is a default class. From here, you can invoke other seeders classes as well.

Install Laravel Project

Eventually, to show you the demo of database seeder in laravel, we need to install a fresh laravel project from the beginning. If you want, you can skip this step, but only if you have already installed the application.

composer create-project laravel/laravel laravel-database-seeder --prefer-dist

Above, command conjugate entire project files in one folder. Then, we have to get inside the project folder.

cd laravel-database-seeder

Establish Database Connection

We have established a new laravel project, and the further step is to set up a database with MySQL. We write the entire memoir inside the MySQL database, such as creating a database, table, or seeding the values inside the table.

Open your .env file and place the following code, it makes the frequent connection between laravel and database to manage the data.

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

If you are using MAMP local server in macOs; make sure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

Manage Model and Migrations

As per the MVC framework, the Model is believed to handle the business logic of the application. Model is a foundational class that preferably describes the logical architecture and relationship of a data table in the database.

You must also know that every data table has a corresponding model, which communicates data.

Run artisan class to create an Employee model:

php artisan make:model Employee -m

Open database/migrations/timestamp_employee_table.php file and add the given below code.

public function up()
{
    Schema::create('employees', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email')->unique();
        $table->string('phone');            
        $table->string('department');
        $table->string('dob');
        $table->timestamps();
    });
}

Open app/Models/Employee.php and define the modal values in the $fillable prop.

<?php

namespace App\Models;

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

class Employee extends Model
{
    use HasFactory;
    public $fillable = [
        'name',
        'email',
        'phone',
        'department',
        'dob',
    ];
}

To run migration execute the given below command.

php artisan migrate

Create Seeder

We have to run the following command to create the Seeder specifically for the Employee table.

php artisan make:seeder EmployeeSeeder

Ultimately the above command generated the seeder in the database/seeds/EmployeeSeeder.php file. No wonder, if you create more seeds, then they will also be kept here.

public function run()
{
    Employee::create([
        'name' => 'John Doe',
        'email' => 'doejohn@gmail.com',
        'phone' => '1234567890',
        'department' => 'hr',
        'dob' => '2010-01-03',
    ]);
}

So, we have configured the following values that will be stored in the database.

  • name
  • email
  • phone
  • department
  • dob

If you require to create more database seeder files, then you can go for it. To generate boundless database seeders use the above command.

Define Additional or Multiple Seeders

This tutorial has made us familiar with the single seeder as if creating a single seeder and calling it. Now, what if you need to generate multiple seeders, any idea?

Well, not to worry. You have to re-use the seeder command to generate a new seeder, which is as follows.

php artisan make:seeder MyNewSeeder

After that, you have to define the MyNewSeeder inside the DatabaseSeeder class, and every seeder class should be conjugated here only from the calling purpose.

Keep in mind this is the usual but foundational step, and it needs to be followed every time you create a new seeder or for calling up multiple database seeders.

/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
    $this->call([
        EmployeeSeeder::class,
        MyNewSeeder::class,
        OtherNewSeeder::class,
    ]);
}

Ultimately, after writing a new seeder, you might require to regenerate Composer’s autoloader:

composer dump-autoload

To genuinely comprehend the larval workings, i would like to bring it to your attention that you can specifically use –class option to seed the required class, particularly. Though, by default the db:seed artisan command seeds the DatabaseSeeder class.

php artisan db:seed

php artisan db:seed --class=YourSeederClass

The database seeding can also be done using the following command.
This command is responsible for dropping all tables and re-initiate the migrations. Use it only when you want to rebuild your database.

php artisan migrate:fresh --seed

Run Seeders and Migrate

Now, we have reached to almost the very last step of this tutorial, entire memoir is likely to end in here.

Open database/seeds/DatabaseSeeder.php define your database seeder class in DatabaseSeeder class.

<?php

use Illuminate\Database\Seeder;

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

Finally, if you are done with it, then execute the mentioned-below command to run run all the defined seeders.

php artisan db:seed

Summary

Eventually, the Laravel Database Seeder tutorial with example has been completed.

I hope you must have assimilated all the steps that i have shared with you related to how database seeder works in laravel with example.

If anyhow, any of the steps seemed vague to you, then do share feedback with me. It will help me to improve, thanks a lot artisans in advance.