Nisha Sharma
Nisha Sharma

Reputation: 255

How to add new column to existing table in laravel

I am adding new column name title in my table tasks. But I am getting an error that this column does not exist in that table. Can anybody help me to resolve that error. Here is my code:

php artisan make:migration add_title_to_tasks_table --table="tasks" and then added this code

Schema::table('tasks', function (Blueprint $table) { 
  $table->string('title');
});

to new table file created

Upvotes: 0

Views: 14389

Answers (3)

Saiyan Prince
Saiyan Prince

Reputation: 4020

Do the following:

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::table('tasks', function (Blueprint $table) {
       $table->string('title')->after('your-column-name');
    });
}

Replace 'your-column-name' with your existing column name.

Save the file. From terminal, execute:

php artisan migrate

The above command will add the column to your table.

You are getting that error because you are not running the migrate command. Whenever you create a migration file, you must execute the above command in order to see the changes in your database table.

Also, if the new column does not exist in the models $fillable property, you will have to add it there as well..

/**
 * The attributes that are mass assignable.
 *
 * @return  array
 */
protected $fillable = [
    'title', // <-- new column name
    // .. other column names
];

Failing to do update the $fillable property will result in MassAssignmentExecption.

Upvotes: 1

Sunny Kumar
Sunny Kumar

Reputation: 33

For those who are new to laravel and looking for a solution, please follow the steps 1). php artisan make:migration add_title_to_tasks_table --table="tasks"

2). Edit the newly created file in the migrations folder and add the below.

public function up() {
    Schema::table('tasks', function (Blueprint $table) {

        $table->string('title')->after('id');

       // to change column datatype or change it to `nullable` 
       // or set default values , this is just example

       $table->string('title')->default('Test')->change(); 

    });
}

3). Run the migrations command.

php artisan migrate

Upvotes: 3

Mayank Majithia
Mayank Majithia

Reputation: 1966

To Alter table and add column.

     /**
     * Run the migrations.
     *
     * @return void
     */
    public function up() {
        Schema::table('tasks', function (Blueprint $table) {

            $table->string('title')->after('id');

           // to change column datatype or change it to `nullable` 
           // or set default values , this is just example

           $table->string('title')->default('Test')->change(); 

        });
    }

You can refere documentation here, Laravel Migration

Upvotes: 4

Related Questions