Home > database >  How to change the name of 'name' column in the 'users' table?
How to change the name of 'name' column in the 'users' table?

Time:02-01

I have a Laravel app with the 'users' table. I want it (the table) to have 'username' column instead of 'name' column, i.e. structure like this:

id username email password ...etc.
1 Username 1 [email protected] xEvehgv#52... ...
2 Username 2 [email protected] dkjbg#%R!D... ...

How can I do this with the help of Laravel 9? Thank you in advance!

CodePudding user response:

Note: changing the column name in the users' table is not a good idea because a lot of packages use the default name of the table instead you can add a new column with your customer name

for example

    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('username');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

otherwise, you can achieve this by going to database/migrations/_create_users_table.php

    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('username');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

and also you have run migrations

php artisan migrate

or

php artisan migrate:refresh

CodePudding user response:

To rename the 'name' column to 'username' in the 'users' table use the following command:

php artisan make:migration rename_name_to_username_in_users

This will create a new migration file. In the file, you can use the table method with the renameColumn() method:

public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->renameColumn('name', 'username');
    });
}

Finally, run the migration.

php artisan migrate
  • Related