Full-text search

Contents
Fulltext index
whereFullText
Ranking note
Keep a scope

Fulltext index

LIKE searches scan letter by letter and slow down as tables grow. A fulltext index flips the work around: the database pre-builds a word map once, then answers word searches from the map instead of re-reading every row.

Schema::table("posts", function (Blueprint $table) { $table->fulltext(["title", "body"]); });

whereFullText

The whereFullText method asks the database for rows that contain your words, most relevant first. Pass the indexed columns and the search text, then use the result like any other collection of models.

$hits = Post::whereFullText(["title", "body"], "fresh bread")->get(); foreach ($hits as $post) { echo $post->title . "\n"; }

Ranking note

Fulltext search ranks by relevance, not by date or id. A post that repeats your words in the title outranks one that mentions them once at the bottom, so the first page of results already reflects what the reader most likely wants.

Do not promise exact ordering to users beyond that promise. Relevance is a score, not a sort key - phrase it as best matches first and nobody will be surprised.

Keep a scope

Wrap the query in a local scope so every search in the project spells the columns the same way. One scope means one place to add a column later, instead of a hunt through controllers.

public function scopeSearch($query, string $term) { return $query->whereFullText(["title", "body"], $term); } $hits = Post::search("fresh bread")->get();

Next: Capstone: blog

Article author: Arthur Isaev

Related articles
Development with PHP
What is Laravel and where it runs
Install Laravel
Your first route
Controllers
Blade basics
Blade advanced
Migrations
Eloquent models
Relationships
Query builder
Seeders and factories
Validation
Auth intro
Hand-rolled login
Middleware
Service container
Config and env
Artisan commands
Events and listeners
Queues
Mail
Cache
Sessions in Laravel
CSRF
Hashing
Sanctum tokens
API resources
Gates and policies
Notifications
Scheduler
Filesystem
Localization
Testing
HTTP tests
Collections
Carbon dates
Pagination
File uploads
Eloquent advanced
Transactions and locks
Deployment
Debugbar and dd
Broadcasting
Full-text search
Capstone: blog
Capstone: JSON API
Capstone: shop cart
Performance: kill N+1
Modern Laravel tour
Hero roadmap: the whole course on one page

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: