Using query builder for adding fulltext index in Laravel

Viewed 3306

This is the query for adding fulltext index in MySQL:

ALTER TABLE `TableName`
ADD FULLTEXT INDEX `IndexName` (`ColumnName`);

But How can I use Laravel query builder to add fulltext index?

3 Answers

On Laravel >= 6.15.0 you can extend Illuminate\Database\Schema\Grammars\MySqlGrammar and Illuminate\Database\Schema\Blueprint classes like this (e.g. on boot() method of your AppServiceProvider):

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\Grammars\MySqlGrammar;
use Illuminate\Support\Fluent;

Blueprint::macro('fulltext', function ($columns, $name = null, $algorithm = null)
{
    return $this->indexCommand('fulltext', $columns, $name, $algorithm);
});

Blueprint::macro('dropFulltext', function ($index)
{
    return $this->dropIndexCommand('dropIndex', 'fulltext', $index);
});

MySqlGrammar::macro('compileFulltext', function (Blueprint $blueprint, Fluent $command)
{
    return $this->compileKey($blueprint, $command, 'fulltext');
});

And use it on your migrations like this:

Schema::table('flights', function (Blueprint $table) {
    $table->fulltext(['name', 'airline']);
});

//reverse the migration
Schema::table('flights', function (Blueprint $table) {
    $table->dropFulltext(['name', 'airline']);
});

For multiple Columns/Fields

DB::statement('ALTER TABLE Database.TableName ADD FULLTEXT fulltext_index (Col_1, col_2, col_3)');
Related