Database seeding in laravel with example

What is Database Seeding?

Database seeding is the process of seeding a database with actual or dummy data, according to Wikipedia. Seeding a database is the process of providing an initial collection of data to a database after setup. It’s especially beneficial when we need to populate the database with data that we’ll need later.

Why is database Seeding required?

Database Seeding is required when we went to add testing data into our application which looks exactly entered by a user. Testing is another major use of database seeding in Laravel.

Suppose one of our application’s functionality is searching, so whenever the user enters a query it will show a few results ranked from thousands of data from our database. In searching applications, response time plays a major role. So for testing response time to search thousands of records, we need to add those records to our database. Manually adding those data can be time-consuming and stressful but with database seeding, it becomes easier. In addition, we can control data duplicity and data type validation.

Laravel includes the ability to seed your database with data using seed classes. All seed classes are stored in the database/seeders directory. The database\seeders\DatabseSeeder.php helps us to manage the order of database seeding into Laravel.

Creating Model and Migration

Laravel is an MVC Framework and Model is fundamentally the base class for application logic. In the Laravel application, the Model communicates with the database and is responsible for each piece of data.

Let’s make a model with migration for posts with the below command.

php artisan make:model Post -m

Here, we are planning for a mass assignment so we need to add our fields into a fillable array.

<?php

namespace App\Models;

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

class Post extends Model
{
    use HasFactory;

    protected $fillable = [
        'title',
        'description',
        'date',
        'name'
    ];
}

Open the database/migrations/timestamp_posts_table.php file and let’s define the database structure for the posts table.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('description');
            $table->date('date');
            $table->string('user');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

Here, we have defined a database table structure just to save the post title, description, date, user, and timestamps. In the actual model, you can add any number of fields as per your requirement.

To run migration execute the given below command into a terminal:

php artisan migrate

It will generate a database table by name posts.

Create Factory

Here, we will create a seeder with dummy data so we will use factory and faker methods to seed data. The factory is very useful while testing for creating multiple data at a time. Factories return a default set of data by a defined datatype.

To create a factory hit the below command into a terminal :

php artisan make:factory PostFactory

With this command, you will get a new file database\factories\PostFactory.php file. Let’s modify it as per our requirements.

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class PostFactory extends Factory
{
    public function definition()
    {
        return [
            'title' => $this->faker->sentence(),
            'description' => $this->faker->text(),
            'date' => $this->faker->date(),
            'user' => $this->faker->sentence(),
        ];
    }
}

the Faker PHP library, which allows you to conveniently generate various kinds of random data for testing. Here, we have used some faker methods to get appropriate data.

Create Seeder

In this step, we will create a seeder for the post model and configure the factory to create a specific number of records in a database. Enter the below command to create Seeder :

php artisan make:seeder PostSeeder

The above command will create a database/seeders/PostSeeder.php file in your application. Let’s make some changes to call the model factory for creating 100 posts.

<?php

namespace Database\Seeders;

use App\Models\Post;
use Illuminate\Database\Seeder;

class PostSeeder extends Seeder
{
    public function run()
    {
        Post::factory()
            ->count(100)
            ->create();
    }
}

Define Seeder into Database Seeder

While using multiple seeders in our application, sometimes we need to set a hierarchy. With DatabaseSeeder you can set which seeder will execute first and in which order.

With Database Seeder you don’t need to seed every class individually. You can configure all seeders into a database seeder and it will execute.

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    public function run()
    {
        $this->call([
            PostSeeder::class,
        ]);
    }
}

Seeding Database Using Seeders

Finally, We have created our seeder and it’s time to seed our database. Enter the below command into a terminal :

php artisan db:seed

It will seed all your seeders defined in your DatabaseSeeder.

You can seed also seed a single seeder using the below command

php artisan db:seed --class=PostSeeder

In some cases, you need to create a fresh database with seeding then you can use the below command :

php artisan migrate:fresh --seed

Sometimes after creating a new seeder, you face an error. So you might be required to regenerate Composer’s autoloader.:

composer dump-autoload

Conclusion

Here we have taken examples for post table and seed data into it. In the actual product, you need to seed fixed data to our application when you can use Laravel’s database seeding functionality and seed those data with simple commands.

In this example, we used Faker for generating data but you can use CSV, JSON files, excel files, XML data, Arrays, or any other format of data using Seeders. You just need to alter the reading logic for those data.