全局搜索
概述
全局搜索允许你在应用的任何地方搜索所有的资源记录。
设置全局搜索结果标题
要在模型中启用全局搜索,你必须先为资源设置一个 title 属性:
protected static ?string $recordTitleAttribute = 'title';
这一属性用于检索搜索记录结果的标题。
你的资源中需要有编辑页或查看页,这样全局搜索结果才可以链接到对应页面,否则不会返回该资源的结果。
你可以重写 getGlobalSearchResultTitle() 方法进一步自定义标题。它将返回普通文本字符串,或者 Illuminate\Support\HtmlString 或 Illuminate\Contacts\Support\Htmlable 实例。这就允许你在搜索结果标题中渲染 HTML 或者 Markdown。
use Illuminate\Contracts\Support\Htmlable;
public static function getGlobalSearchResultTitle(Model $record): string | Htmlable
{
return $record->name;
}
多字段搜索
如果你想要在资源中搜索多个字段,你可以重写 getGloballySearchableAttributes() 方法。“点语法”让你可以搜索关联的内部:
public static function getGloballySearchableAttributes(): array
{
return ['title', 'slug', 'author.name', 'category.name'];
}
添加额外详情到全局搜索结果
搜索结果可以在标题的下面显示“详情(Details)”,让用户获取更多记录信息。要启用此特性,你必须重写 getGlobalSearchResultDetails() 方法:
public static function getGlobalSearchResultDetails(Model $record): array
{
return [
'Author' => $record->author->name,
'Category' => $record->category->name,
];
}
此例中,记录的分类和作者会显示在搜索结果的标题下面。不过,category 和 author 关联是通过懒加载实现,会导致搜索结果的性能不佳。想要积极加载这些关联,必须重写 getGlobalSearchEloquentQuery() 方法:
public static function getGlobalSearchEloquentQuery(): Builder
{
return parent::getGlobalSearchEloquentQuery()->with(['author', 'category']);
}
自定义全局搜索结果 URL
全局搜索结果会链接到资源的编辑页