Inserting data into tables using database migrations in Laravel 5

In order to insert data in database tables we may use classes to migrate database values. These values will be inserted in an array form.

Example (creating migration class)

C:\wamp\www\laravel>php artisan make:migration add_author
Created Migration: 2015_05_05_130410_add_author

This will produce a template file with standard up and down methods.

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddAuthor extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		//
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		//
	}
}

Adding data code in form of array:

Populated class (2015_05_05_130410_add_author.php)

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddAuthor extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		DB::table('author')->insert(array(
		'name' =>'abc',
		'password' => '123456',
		'created_at'=> date('Y-m-d H:m:s'),
		'updated_at'=> date('Y-m-d H:m:s')
		));

		DB::table('author')->insert(array(
		'name' =>'xyz',
		'password' => '654321',
		'created_at'=> date('Y-m-d H:m:s'),
		'updated_at'=> date('Y-m-d H:m:s')
		));

	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		//
	}

}

Running migrations

C:\wamp\www\laravel>php artisan migrate
Migrated: 2015_05_05_130410_add_author

Sample data

Untitled

Share

You may also like...