Laravel Migrations: How to Rename a Table
Renaming Tables in Laravel
Renaming a table in Laravel is a common task that might arise when you're refactoring your database schema. In this post, we'll walk through how to rename a table in Laravel.
Let’s consider we already have the following clients table:
use Illuminate\Database\Migrations\Migration;use Illuminate\Database\Schema\Blueprint;use Illuminate\Support\Facades\Schema; return new class extends Migration { public function up(): void { Schema::create('clients', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->timestamps(); }); } public function down(): void { Schema::dropIfExists('clients'); }};
Rename the Table Using a New Migration
To rename the clients table to customers, we need to create a new migration file using make:migration artisan command:
php artisan make:migration rename_clients_table_to_customers_table
Update the new migration file like so:
use Illuminate\Database\Migrations\Migration;use Illuminate\Support\Facades\Schema; return new class extends Migration { public function up(): void { Schema::rename('clients', 'customers'); } public function down(): void { Schema::rename('customers', 'clients'); }};
This migration uses Laravel’s built-in Schema::rename() method to rename the table from clients to customers. The down() method ensures you can roll back the change if needed.
Run the migration:
php artisan migrate
The clients table is now renamed to customers.
Stay Updated.
I'll you email you as soon as new, fresh content is published.