laravel 中快速启用生产级搜索需使用 scout 扩展,避免 like 查询与数据库全文索引局限;安装 scout 后配置 meilisearch 驱动,为模型添加 searchable trait,自定义 tosearchablearray() 控制索引字段,通过 scout:import 导入数据,并支持关键词搜索、条件过滤、模糊匹配及实时同步。

要在 Laravel 项目中快速启用可生产使用的搜索功能,必须避开手写 LIKE 查询、避免重复造轮子,且不能依赖数据库原生全文索引的局限性——它不支持中文分词、无相关度排序、无法跨模型聚合结果。
安装 Scout 及选定驱动
执行 Composer 命令安装 Scout 核心包:composer require laravel/scout
发布 Scout 配置文件,生成 config/scout.php:php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
根据部署环境选择驱动:本地开发推荐 Meilisearch(轻量、开箱即用),生产环境若已有 Elasticsearch 集群则复用;【切勿在 .env 中留空 SCOUT_DRIVER】,否则运行时抛出未定义驱动异常。
以 Meilisearch 为例,在 .env 中写入三行:
SCOUT_DRIVER=meilisearchMEILISEARCH_HOST=http://127.0.0.1:7700MEILISEARCH_KEY=masterKey
接着安装 Meilisearch PHP 客户端:composer require meilisearch/meilisearch-php
为模型启用搜索能力
打开要支持搜索的 Eloquent 模型(如 App\Models\Post),在类声明后添加 trait:
use Laravel\Scout\Searchable;class Post extends Model { use Searchable; }
默认情况下,Scout 会索引模型所有字段。若只需搜索标题和内容,重写 toSearchableArray() 方法:
public function toSearchableArray() { return ['title' => $this->title, 'content' => $this->content]; }
这一步能显著减少索引体积,加快同步速度,也避免敏感字段(如 password_hash)意外进入搜索引擎。
导入历史数据到搜索索引
第一步:确保 Meilisearch 服务已运行(meilisearch --master-key "masterKey")。
第二步:执行全量导入命令:
php artisan scout:import "App\Models\Post"
该命令会分块读取数据库记录,逐条发送至 Meilisearch。若模型数据超 10 万条,建议先禁用队列(SCOUT_QUEUE=false)再执行,防止内存溢出或超时中断。
第三步:验证索引是否建立成功——访问 http://127.0.0.1:7700/indexes,确认 posts 索引存在且非空。
在控制器中调用搜索
方法一:基础关键词搜索
$posts = Post::search('Laravel 教程')->get();
方法二:带过滤条件的搜索(需 Meilisearch v1.8+ 或配置自定义规则)
$posts = Post::search('部署')<br>
->where('status', 'published')<br>
->orderBy('created_at', 'desc')<br>
->paginate(15);
方法三:模糊匹配增强(对中文更友好)
在 config/scout.php 的 meilisearch 驱动配置中加入:
'options' => ['typoTolerance' => true, 'synonyms' => []]
这能让 “laravel” 匹配 “larevel”、“larval” 等常见拼写错误,无需额外代码。
启用实时同步
模型创建、更新、删除操作将自动触发索引更新,前提是模型已使用 Searchable trait。
但注意:若批量更新(如 Post::where('id', '>', 100)->update(['status' => 'draft'])),Scout 不会监听,需手动刷新:
Post::where('id', '>', 100)->searchable();
或彻底重建索引:php artisan scout:flush "App\Models\Post" && php artisan scout:import "App\Models\Post"











