PASSWORD RESET

Your destination for complete Tech news

How to add a new column in Laravel migration?

397 0
< 1 min read

To add a new column to a table in Laravel, you can use a database migration. In a migration, you can use the addColumn method of the Schema class to add a new column to a table.

Here is an example of how to add a new column to a table using a Laravel migration:

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

class AddPhoneNumberToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('phone_number')->nullable();
        });
    }

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

In this example, we have a migration class named AddPhoneNumberToUsersTable that adds a new column named phone_number to the users table. The up method is called when the migration is run, and the down method is called when the migration is rolled back.

To run this migration, you can use the php artisan migrate command:

php artisan migrate

This will apply all outstanding migrations, including the AddPhoneNumberToUsersTable migration.

Note that you will need to replace users with the actual name of your table and phone_number with the name of the column you want to add. You can also customize the column type and other options using the various methods of the Blueprint class.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.