Adding fields to a new database using migrate

Leave a comment

August 6, 2016 by movefirstblog

We’ve previously looked at how to Create a new database table using migrate.

Now we can add fields to our empty database.

For this we need a new migrate script.

But first let’s take a look what migrate created for us we created our table. Here’s the code that was generated for us:

<?php

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

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
        });
    }

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

I won’t go into too much detail here but notice the two functions public function up() and public function down().

The up() function creates the fields that we specify in our database.

The down() function drops the table if we choose to rollback changes.

Note that the up() function automatically inserts two fields for us, an auto-incremented id field and a timestampfield.

Let’s add some additional fields to our new products table.

We do this by adding code to our up() function.

We’ll add fields for a product id, the product’s name, a brief description of the product and its price.  We can do this by replacing the code in the existing up() function with the following:

$table->increments('id');
$table->integer('product_id');
$table->string('product_name');
$table->text('product_description');
$table->decimal('product_price', 10, 2);
$table->timestamps();

Once we’re happy with our new migration code we can run it by using:

php artisan migrate

(I’ve only touched on the very basic utilisation of migrations here and for more details on this topic I recommend you take a look at http://laravelbook.com/laravel-migrations-managing-databases/ which contains more details on the above and a very useful list of data types).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: