Change Table Name Using Laravel Migration

Hello bro,

In this post we will focus on the main operations we need to do on any Laravel project, for example, will learn you how to change column type in the migration file. step by step explain how to rename column names in the migration file. another one is how to rename the table names using the migration file,  follow the below step to learn how to do it.
I will give you two examples of main operations can we use in all Laravel versions from 5 to above.

First of all we need to install "doctrine/dbal" composer package.

composer require doctrine/dbal

After successfully installing the composer package we can proceed to explain the operations.

we can easily rename table name's using Schema rename method. so let's do this, for example, we have a table called "articles" and we need to change the name to a new one called "posts"

  • Create Migration File
php artisan make:migration RenameArticlesTable

 

Then use the rename method from Schema to do it with syntax Schema::rename('old_table_name', 'new_table_name');



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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::rename('posts', 'articles');
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
};

Now, you can run the migration command:

php artisan migrate

Thanks

Comments

Leave a Comment

All Categories

Tags