Monday 6 March 2017

Topic 8 - Database Migration and Seeding

Migrations


Today we are going to learn to migrate to some of our database fields that we create inside database/migrations folder into or local database. Please follow these steps :

1: Php Artisan Command Migrate

php artisan make:migration alumnis



2: Migration Structure

class CreateAlumnisTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
      Schema::create('alumnis', function (Blueprint $table) {
          $table->increments('id');
          $table->string('name');
          $table->string('icno');
          $table->string('matrixno');
          $table->string('email');
          $table->timestamps();
          $table->softDeletes();
          $table->integer('created_by')->nullable();
          $table->integer('updated_by')->nullable();
          $table->integer('deleted_by')->nullable();
      });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
     public function down()
    {
        Schema::dropIfExists('alumni');
    }
}

3. Run Migration 

php artisan migrate 











4. Check Status Migrate

php artisan migrate:status














Seedings


However , after we migrate our migration file into our local database we cant leave them empty without example data. Seeding is more like initial data where we can insert dummies data to test with. Please follow these steps for better understanding :


1: Php Artisan Command Seeder


php artisan make:seeder AlumniSeeder
php artisan make:seeder -----> php artisan command
AlumniSeeder ----> table seeder



2: Class Seeder Structure


<?php

use Illuminate\Database\Seeder;

class AlumniSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
      DB::table('alumnis')->insert([
           'name' => str_random(10),
           'icno' => str_random(10),
           'matrixno' => str_random(10),
           'email' => str_random(10),
       ]);
    }
}
3: Run Seeders File

By default , db:seed command runs all seeder files inside database/seeds folder. However we can specify seeder class by putting --class option to run individually.
php artisan db:seed
php artisan db:seed --class:AlumniSeeder


References 

https://laravel.com/docs/5.4/migrations#creating-tables
https://laravel.com/docs/5.4/seeding

No comments:

Post a Comment