DEV Community

Cover image for Laravel 8 Seeder Tutorial and Example
Code And Deploy
Code And Deploy

Posted on

Laravel 8 Seeder Tutorial and Example

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/laravel/creating-a-seeder-in-laravel-8

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

Here is the 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
Enter fullscreen mode Exit fullscreen mode

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'
        ]);
    }
}
Enter fullscreen mode Exit fullscreen mode

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

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

php artisan db:seed
Enter fullscreen mode Exit fullscreen mode

or in a specific command for a seeder class:

php artisan db:seed --class=CreatePostsSeeder
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/laravel/creating-a-seeder-in-laravel-8 if you want to download this code.

Happy coding :)

Top comments (0)