Module

Seeders

Introduction

This is a Guide to use Seeders in VaahCMS.

Basically Seeder is a class used to seed the database with data. In VaahCMS All the seed classes are stored in the Database\Seeds directory.
Follow below image for reference: seeder directory


Types of Seeders in VaahCMS

There are two types of Seeders in VaahCMS:

  1. DatabaseTableSeeder
  2. SampleDataTableSeeder

Follow below image for references: types of seeder We will get to know about both these Seeders one by one.

1. DatabaseTableSeeder :

This Seeder is used to seed the database with necessary data. All the necessary functions, which are required for the module and theme are placed inside run method of DatabaseTableSeeder.
Follow below image for reference:

DatabaseTableSeeder

The run method of DatabaseTableSeeder is called whenever any module or theme is activated by the user and it seeds the database with the data.


2. SampleDataTableSeeder :

SampleDataTableSeeder is used to seed test data into the database for the module or the theme. Whenever we want to insert test data into the database we can use run method of this Seeder class to seed the test data. To use SampleDataTableSeeder we need to click on import sample data for the particular module or the theme.
Follow below image for reference:

import sample data

Once we click on this Import Sample Data button run method of SampleDataTableSeeder is called and data is seeded into the database.


Example:

Lets assume that we want to add 10 records in tr_blogs table for testing purpose. In this case we will be editing SampleDataTableSeeder.php file.

<?php
namespace VaahCms\Modules\Travel\Database\Seeds;


use Illuminate\Database\Seeder;
use Faker\Factory;
use Illuminate\Support\Str;
class SampleDataTableSeeder extends Seeder
{
   /**
    * Run the database seeds.
    *
    * @return void
    */
   public function run()
   {
       $this->seeds();
   }

   /**
    * Run the database seeds.
    *
    * @return void
    */
   function seeds()
   {
       $this->seedBlogs();
   }

   function seedBlogs()
   {
       $faker = Factory::create();
       $num_blogs = 10;

       $list = [];
       for ( $i = 0; $i < $num_blogs; $i ++ ) {
           $list[$i] = [
               'name'         => $faker->name,
               'slug'       => Str::slug($faker->name),
               'is_active'  => 1,
               'created_at'    => \Carbon::now()->format( 'Y-m-d H:i:s' ),
               'updated_at'    => \Carbon::now()->format( 'Y-m-d H:i:s' ),
           ];
           $exist = \DB::table( 'tr_blogs' )
               ->where( 'name', $list[$i]['name'] )
               ->first();
           if($exist)
           {
               continue;
           }
       }

       if(count($list) > 0 )
       {
           \DB::table( 'tr_blogs' )->insert( $list );
       }
   }



}

Now we just need to click on Import Sample Data button, records will be inserted in the tr_blogs table in database.


Copyright © 2024