Hello developers! If you've ever found yourself needing to make changes to your database structure in a Laravel project, you're in the right place. Today, we're going to dive into a common scenario: adding and dropping a primary key from a table.
Now, you might be wondering, "Why is this necessary?" Well, as our projects evolve, so do our requirements, and sometimes, adjustments to the database become inevitable.
In this guide, we'll walk through the process of adding a primary key column using Laravel 10 migrations with Doctrine/DBAL.
In this article, we'll see how to drop the primary key in laravel 10 migration, laravel 10 migration drop primary key, drop column in laravel migration, and how to remove the primary key laravel 8/9/10.
Create a new migration using the following command:
php artisan make:migration create_products_table
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.
*/
public function up(): void
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('products');
}
};
Make sure you have Doctrine/DBAL installed in your Laravel project. You can install it using Composer:
composer require doctrine/dbal
Create a new migration using the Artisan command:
php artisan make:migration drop_primary_key
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.
*/
public function up(): void
{
Schema::table('products', function (Blueprint $table) {
$table->integer('id')->unsigned()->change();
$table->dropPrimary('id');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('products');
}
};
Run the Migration:
Finally, run the migration to apply the changes to the database:
php artisan migrate
You might also like: