Adding a new column to the existing table
We are going to add 'username' column to the users table.
To add this column to the existing users table we just need to create a new migration table and link it the the users table
php artisan make:migration add_username_to_users_table --table=users
We are going to edit this migration table up() function and add the username column to come after name and allow it to be nullable
public function up(): void {
Schema::table('users', function (Blueprint $table) {
$table->string('username')->nullable()->after('name');
});
}
Now we migrate our username column would be visible in our DB table.
php artisan migrate
Removing a column from the existing table
We are going to remove the 'username' column from the users table.
To do this we're going to follow steps as when adding but a different migration table name. So, first we make a migration table and link it to the users table
php artisan make:migration remove_username_from_users_table --table=users
To delete the username column would edit the up() function and a dropColumn to it 👇
public function up(): void {
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('username');
});
}
Now we migrate and our username column would be removed from the DB
php artisan migrate
Modifying our column type in laravel migration table
First things first, to be able to edit our column type in laravel we need a package 'doctrine/dbal'. So let's install it
composer require doctrine/dbal
We would be modifying the name column from "string" to "text"
Now we create the migration table that we would be using the change the column type
php artisan make:migration change_name_from_string_to_text_in_users_table --table=users
Then we create a table column in the up() function that would modify the existing name column
public function up(): void {
Schema::table('users', function (Blueprint $table) {
$table->text("name")->change();
});
}
Don't forget to migrate
php artisan migrate
Our name column is using the text now instead of string and that's all