Table of contents

Creating a Seeder in Laravel 8

In this post, I will share an example of how to create a Laravel 9 seeder. Seeder is important to initialize our default data to our database.

 

Here is an example:

 

Step 1: Create Laravel Seeder

Let's create a Laravel seeder for our posts table. Run the following command:

php artisan make:seeder CreatePostsSeeder

 

Step 2: Insert Data

Once our Laravel seeder is generated kindly to the database/seeders directory. Open the CreatePostsSeeder.php and you will see the following code:

<?php

namespace Database\Seeders;

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

class CreatePostsSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Post::create([
            'title' => 'Post 1',
            'description' => 'Description for post 1',
            'body' => 'Body for post 1'
        ]);

        Post::create([
            'title' => 'Post 2',
            'description' => 'Description for post 2',
            'body' => 'Body for post 2'
        ]);

        Post::create([
            'title' => 'Post 3',
            'description' => 'Description for post 3',
            'body' => 'Body for post 3'
        ]);

        Post::create([
            'title' => 'Post 4',
            'description' => 'Description for post 4',
            'body' => 'Body for post 4'
        ]);

        Post::create([
            'title' => 'Post 5',
            'description' => 'Description for post 5',
            'body' => 'Body for post 5'
        ]);
    }
}

 

As you can see in the run() method we added inserting post data.

 

Now let's save the data by running the following commands below:

php artisan db:seed

 

or in a specific command for a seeder class:

php artisan db:seed --class=CreatePostsSeeder

 

Once done it will save the seeder data.

 

You can also rollback the rerun the migrations with the command below:

php artisan migrate:refresh --seed

 

The migrate:refresh --seed is a shortcut of the following commands below:

php artisan migrate:reset     # rollback all migrations
php artisan migrate           # run migrations
php artisan db:seed           # run seeders

 

I hope it helps. Thanks for reading :)