Spread the love

In our last article we learnt about how to create seeder in laravel but sometimes we only need to run a specific seeders rather then running all so in this article we will cover to run a specific seeder. We will use a simple example of article class and will run only that specific seeder using artisan command.

Below is the command to run specific seeder and we passed an option –class to run specific seeder class

php artisan db:seed --class=NameSeeder

Before start I assume you well known to database and and How to make database connection in Laravel 8 ?

Let’s start the article run specific seeder class with step by step process

Step 1: Create a seeder class

Very first step is to create the seeder class using PHP artisan command as below

php artisan make:seeder ArticleSeeder

Above command will create a file in folder database/seeders and the code will be in file

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

class ArticleSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //
    }
}

Step 2: Modify Generated Class to Seed the Table

In previous step we created the class, now modify it according to our need for example in our articles table we have below schema

CREATE TABLE `articles` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `title` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `picture` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `body` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

then we need to change the ArticleSeeder class as below

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class ArticleSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
          for($count=0;$count<10;$count++){
            DB::table('articles')->insert([
                'title' => Str::random(10),
                'email' => Str::random(10).'@gmail.com',
                'body'  => Str::random(100),
                'updated_at' => date("Y-m-d H:i:s"),
                'created_at' => date("Y-m-d H:i:s"),
                
            ]);
        }
    }
}

As you can see we have added the for loop to run the insert query 10 times and it will generate 10 records in article table.

Step 3: Run the seeders

RUn the specific seeder class using artisan command as below

php artisan db:seed --class=ArticleSeeder

This will create 10 records in table.

Leave a Reply