简体   繁体   中英

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

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

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

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

Hope this helps you out. Happy Coding. Cheers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM