Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

laravel
commmunitycreator

How to add columns to an existing database table

Chinweuba Elijah Azubuike

Overview

Have you ever wanted to add an extra column to your database table without editing its original schema or losing data? This shot will cover exactly how to do that.

Let’s assume you have an existing model with the following schema:

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }
   public function down()    {
        Schema::dropIfExists('users');
    }
}

Maybe after a while, you decide to add a column, like phone_number. If you were to do that from the original schema, you might run php artisan migrate, which would erase existing data from the table.

So, the best way to do this is to run a typical command, as shown below:

php artisan make:migration add_phone_number_column_to_users --table users

Head over to your migration directory and you will find a file like add_phone_number_column_to_users.php.

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddPhoneNumberColumnToUsers extends Migration
{
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string(‘phone_number’);

        });
    }
   public function down()    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn(‘phone_number’);

        });
    }
}

We run the php artisan migrate command.

Now, check your database, and it should have the added column.

Summary

Complementary tables are simply columns we decide to add to our existing database table in order to avoid distorting data in the existing table.

RELATED TAGS

laravel
commmunitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring