Monday 4 January 2016

Adding Foreign Key on the Existing Table in Laravel 5.2 using php artisan command

To add a foreign key to the existing Table in Laravel 5.2 using php artisan command

Please run the below command:

  
// user_id: This is the name of your column on this format
// property_list: This is the name of reference table (e.g. to table, not from table)

$ php artisan make:migration add_foreign_key_for_user_id_column_to_property_list_table --table=property_list

Find below the sample class of the foreign key migration table
 
class AddForeignKeyForUserIdColumnToPropertyListTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('property_list', function (Blueprint $table) {
            //
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onUpdate('NO ACTION')->onDelete('NO ACTION');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('property_list', function (Blueprint $table) {
            //
            $table->dropForeign('property_list_user_id_foreign');
        });
    }
}


No comments:

Post a Comment

Please post any queries and comments here.