How to add index to an existing column in Laravel
Categorized as Laravel
If you want to add a new index to some columns in your existing table, you can do it pretty easily with Laravel migration. First, create the migration:
php artisan make:migration "Add index to a column in categories table" --table=categories
Then edit the migration php file. In this example, we are adding two indexes to a table, parent_id
and slug
:
<?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()
{
Schema::table('categories', function (Blueprint $table) {
$table->index(['parent_id', 'slug']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('categories', function (Blueprint $table) {
//
});
}
};