Igor Simic
8 years ago

Use FULLTEXT search in Laravel



Implementing Full-Text search in Laravel

Much better and faster way to search MySql DB is to use FULLTEXT search instead of using simple 'LIKE'.

How to implement in Laraval
Create migration
<?php
public function up()
	{
		Schema::create('snippets', function (Blueprint $table) {
			$table->engine = 'MyISAM'; // means you can't use foreign key constraints
			$table->text('content');
			$table->string('title',250);
                        .....
		});

		DB::statement('ALTER TABLE snippets ADD FULLTEXT search(title, content)');
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::table('snippets', function($table) {
	    	$table->dropIndex('search');
		});
		Schema::drop('snippets');
	}

Use it inyour query

<?php
$query_data = new Snippet();
$query_data = $query_data->whereRaw( MATCH (title,content) AGAINST ('$searchTerm' IN BOOLEAN MODE)");
$search_result = $query_data->get();


SQL example:

SELECT * FROM `snippets` WHERE MATCH(title,body) AGAINST('PHP' IN BOOLEAN MODE);