Laravel

How to rename a column with a foreign key in Laravel

This database originally used “owner_id” as the column name for the owner of each row, however, the actual model being referenced was a “User”. Here’s how I changed the name of the column (which happened to have a foreign key on it) via Laravel migration:

<?php

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(): void
    {
        Schema::table('chirps', function (Blueprint $table) {
            $table->dropForeign('chirps_owner_id_foreign');
            $table->renameColumn('owner_id', 'user_id');
            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(): void
    {
        Schema::table('chirps', function (Blueprint $table) {
            $table->dropForeign('chirps_user_id_foreign');
            $table->renameColumn('user_id', 'owner_id');
            $table->foreign('owner_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');
        });
    }
};