Fulltext search into Laravel

Tram Ho

1. Add an index in migration

Fulltext is an index type that accepts 1 or more columns. Because Laravel doesn’t have a function that supports fulltext indexing, we have to write it ourselves.

Here we use the Storage Engine MyISAM instead of InnoDB

2. Define a searchable field Go to the User model and add the following code. We need to add the correct column name defined in step 1.

If the column names are not defined correctly, MySql will not be able to find the index and will return an SQLSTATE [HY000] error: General error: 1191 Can’t find FULLTEXT index matching the column list.

3. Create Trait

In a project, there is not only one model to search. Instead of writing code search in all those models, we’ll create a trait to avoid code duplication. Create Traits folder in app and fulltextsearch.php file

4. Config

-Because MySql does not index words with small characters (the default is 4), we will have to change the ft_min_word_len field below the [mysqld] line in my.cnf file. on ubuntu: edit the file in /etc/mysql/my.cnf. If you use XAMPP then edit it in the [xampp installation directory] /etc/mysql/my.cnf

-Also, if the search term is stopword, MySQL will ignore the word. If you want to remove the stopword, add the line ft_stopword_file = “” into the my.cnf file.

5. Use


This article I translated from page https://arianacosta.com/php/laravel/tutorial-full-text-search-laravel-5/

Share the news now

Source : Viblo