To implement full-text search in Laravel, first add a full-text index in the migration using $table->fullText(['title', 'content']); then use whereFullText(['title', 'content'], $query) in queries for efficient searching; encapsulate logic in a model scope for reusability and fall back to LIKE if needed.
To create a full-text search in Laravel, you don't need to build everything from scratch. Laravel provides tools and conventions that work well with database-level full-text indexing and querying. Here's how you can implement it effectively using MySQL or PostgreSQL, which support full-text search natively.
Set up Full-Text Index in Migration
If you're using MySQL or PostgreSQL, you can add a full-text index on the columns you want to search. For example, if you have an articles table and want to search through title and content, update your migration:
database/migrations/xxxx_create_articles_table.php
In the schema definition:
- $table->text('title');
- $table->text('content');
- $table->fullText(['title', 'content']); // This creates a full-text index
Use Where Full-Text in Queries
Laravel allows you to use whereFullText method (available in Laravel 8 ) for full-text searches on MySQL and PostgreSQL.
Example in a controller:
- $query = request('search');
- $articles = Article::whereFullText(['title', 'content'], $query)->get();
This automatically generates the correct SQL (MATCH...AGAINST in MySQL) and leverages the full-text index for better performance.
Handle Search Logic in Model or Service
You can encapsulate the search logic inside your model for reusability:
app/Models/Article.php
- public function scopeSearch($query, $searchTerm)
- {
- ??if (! $searchTerm) return $query;
- ??return $query->whereFullText(['title', 'content'], $searchTerm);
- }
Now use it like:
- Article::search('Laravel full-text')->get();
Fallback for Basic Search (Optional)
If full-text isn’t available or you’re on SQLite (which has limited support), you can fall back to LIKE queries — though this is slower and less accurate:
- $articles = Article::where('title', 'LIKE', "%$query%")
- ??->orWhere('content', 'LIKE', "%$query%")->get();
For advanced needs like relevance scoring, language support, or large-scale applications, consider Scout with drivers like Algolia or Meilisearch. But for most apps, native full-text with whereFullText works great.
Basically just add the index, use the right query method, and keep it simple.
The above is the detailed content of How to create a full-text search in Laravel?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PolymorphicrelationshipsinLaravelallowamodellikeCommentorImagetobelongtomultiplemodelssuchasPost,Video,orUserusingasingleassociation.2.Thedatabaseschemarequires{relation}_idand{relation}_typecolumns,exemplifiedbycommentable_idandcommentable_typeinaco

Yes,youcancreateasocialnetworkwithLaravelbyfollowingthesesteps:1.SetupLaravelusingComposer,configurethe.envfile,enableauthenticationviaBreeze/Jetstream/Fortify,andrunmigrationsforusermanagement.2.Implementcorefeaturesincludinguserprofileswithavatarsa

Create language files: Create subdirectories for each language (such as en, es) in the resources/lang directory and add messages.php file, or use JSON file to store translation; 2. Set application language: read the request header Accept-Language through middleware or detect language through URL prefix, set the current language using app()->setLocale(), and register the middleware in Kernel.php; 3. Use translation functions: use __(), trans() or @lang in the view, and use __() that supports fallback; 4. Support parameters and plural: Use placeholders in translation strings such as: n

Laravel's TaskScheduling system allows you to define and manage timing tasks through PHP, without manually editing the server crontab, you only need to add a cron task that is executed once a minute to the server: *cd/path-to-your-project&&phpartisanschedule:run>>/dev/null2>&1, and then all tasks are configured in the schedule method of the App\Console\Kernel class; 1. Defining tasks can use command, call or exec methods, such as $schedule-

Using Laravel to build a mobile backend requires first installing the framework and configuring the database environment; 2. Define API routes in routes/api.php and return a JSON response using the resource controller; 3. Implement API authentication through LaravelSanctum to generate tokens for mobile storage and authentication; 4. Verify file type when uploading files and store it on public disk, and create soft links for external access; 5. The production environment requires HTTPS, set current limits, configure CORS, perform API version control and optimize error handling. It is also recommended to use API resources, paging, queues and API document tools to improve maintainability and performance. Use Laravel to build a safe,

LaravelusesMonologtologmessagesviatheLogfacade,withdefaultlogsstoredinstorage/logs/laravel.log.Configurechannelsinconfig/logging.phptocontroloutput;thedefaultstackchannelaggregatesmultiplehandlerslikesingle,whichwritestoafile.UseLog::info(),Log::warn

Ensure that there is a remember_token column in the user table. Laravel's default migration already includes this field. If not, it will be added through migration; 2. Add a check box with name remember in the login form to provide the "Remember Me" option; 3. Pass the remember parameter to the Auth::attempt() method during manual authentication to enable persistent login; 4. "Remember Me" lasts for 5 years by default, and can be customized through the remember_for configuration item in config/auth.php; 5. Laravel automatically invalidates remember_token when password changes or user deletes. It is recommended to use HTTPS to ensure security in the production environment; 6

Toimplementfull-textsearchinLaravel,firstaddafull-textindexinthemigrationusing$table->fullText(['title','content']);thenusewhereFullText(['title','content'],$query)inqueriesforefficientsearching;encapsulatelogicinamodelscopeforreusabilityandfallba
