laravel-cross-eloquent-search

laravel-cross-eloquent-search

Laravel跨模型搜索包,简化Eloquent全文检索

laravel-cross-eloquent-search是一个专为Laravel设计的跨Eloquent模型搜索包。它支持多模型搜索、排序、分页、作用域查询和关系预加载。该包提供全文搜索、相关性排序、通配符匹配等功能,无需第三方依赖。适用于PHP 8.2+和Laravel 10.0+,可有效简化复杂的搜索实现。

LaravelEloquent搜索数据库查询Github开源项目

Laravel Cross Eloquent Search

Latest Version on Packagist run-tests Total Downloads Buy us a tree

This Laravel package allows you to search through multiple Eloquent models. It supports sorting, pagination, scoped queries, eager load relationships, and searching through single or multiple columns.

Sponsor Us

<img src="https://inertiaui.com/visit-card.jpg" />

❤️ We proudly support the community by developing Laravel packages and giving them away for free. If this package saves you time or if you're relying on it professionally, please consider sponsoring the maintenance and development and check out our latest premium package: Inertia Table. Keeping track of issues and pull requests takes time, but we're happy to help!

Requirements

  • PHP 8.2 or higher
  • MySQL 8.0+
  • Laravel 10.0+

Features

  • Search through one or more Eloquent models.
  • Support for cross-model pagination.
  • Search through single or multiple columns.
  • Search through (nested) relationships.
  • Support for Full-Text Search, even through relationships.
  • Order by (cross-model) columns or by relevance.
  • Use constraints and scoped queries.
  • Eager load relationships for each model.
  • In-database sorting of the combined result.
  • Zero third-party dependencies

📺 Want to watch an implementation of this package? Rewatch the live stream (skip to 13:44 for the good stuff): https://youtu.be/WigAaQsPgSA

Blog post

If you want to know more about this package's background, please read the blog post.

Installation

You can install the package via composer:

composer require protonemedia/laravel-cross-eloquent-search

Upgrading from v2 to v3

  • The get method has been renamed to search.
  • The addWhen method has been removed in favor of when.
  • By default, the results are sorted by the updated column, which is the updated_at column in most cases. If you don't use timestamps, it will now use the primary key by default.

Upgrading from v1 to v2

  • The startWithWildcard method has been renamed to beginWithWildcard.
  • The default order column is now evaluated by the getUpdatedAtColumn method. Previously it was hard-coded to updated_at. You still can use another column to order by.
  • The allowEmptySearchQuery method and EmptySearchQueryException class have been removed, but you can still get results without searching.

Usage

Start your search query by adding one or more models to search through. Call the add method with the model's class name and the column you want to search through. Then call the search method with the search term, and you'll get a \Illuminate\Database\Eloquent\Collection instance with the results.

The results are sorted in ascending order by the updated column by default. In most cases, this column is updated_at. If you've customized your model's UPDATED_AT constant, or overwritten the getUpdatedAtColumn method, this package will use the customized column. If you don't use timestamps at all, it will use the primary key by default. Of course, you can order by another column as well.

use ProtoneMedia\LaravelCrossEloquentSearch\Search; $results = Search::add(Post::class, 'title') ->add(Video::class, 'title') ->search('howto');

If you care about indentation, you can optionally use the new method on the facade:

Search::new() ->add(Post::class, 'title') ->add(Video::class, 'title') ->search('howto');

There's also an when method to apply certain clauses based on another condition:

Search::new() ->when($user->isVerified(), fn($search) => $search->add(Post::class, 'title')) ->when($user->isAdmin(), fn($search) => $search->add(Video::class, 'title')) ->search('howto');

Wildcards

By default, we split up the search term, and each keyword will get a wildcard symbol to do partial matching. Practically this means the search term apple ios will result in apple% and ios%. If you want a wildcard symbol to begin with as well, you can call the beginWithWildcard method. This will result in %apple% and %ios%.

Search::add(Post::class, 'title') ->add(Video::class, 'title') ->beginWithWildcard() ->search('os');

Note: in previous versions of this package, this method was called startWithWildcard().

If you want to disable the behaviour where a wildcard is appended to the terms, you should call the endWithWildcard method with false:

Search::add(Post::class, 'title') ->add(Video::class, 'title') ->beginWithWildcard() ->endWithWildcard(false) ->search('os');

Multi-word search

Multi-word search is supported out of the box. Simply wrap your phrase into double-quotes.

Search::add(Post::class, 'title') ->add(Video::class, 'title') ->search('"macos big sur"');

You can disable the parsing of the search term by calling the dontParseTerm method, which gives you the same results as using double-quotes.

Search::add(Post::class, 'title') ->add(Video::class, 'title') ->dontParseTerm() ->search('macos big sur');

Sorting

If you want to sort the results by another column, you can pass that column to the add method as a third parameter. Call the orderByDesc method to sort the results in descending order.

Search::add(Post::class, 'title', 'published_at') ->add(Video::class, 'title', 'released_at') ->orderByDesc() ->search('learn');

You can call the orderByRelevance method to sort the results by the number of occurrences of the search terms. Imagine these two sentences:

  • Apple introduces iPhone 13 and iPhone 13 mini
  • Apple unveils new iPad mini with breakthrough performance in stunning new design

If you search for Apple iPad, the second sentence will come up first, as there are more matches of the search terms.

Search::add(Post::class, 'title') ->beginWithWildcard() ->orderByRelevance() ->search('Apple iPad');

Ordering by relevance is not supported if you're searching through (nested) relationships.

To sort the results by model type, you can use the orderByModel method by giving it your preferred order of the models:

Search::new() ->add(Comment::class, ['body']) ->add(Post::class, ['title']) ->add(Video::class, ['title', 'description']) ->orderByModel([ Post::class, Video::class, Comment::class, ]) ->search('Artisan School');

Pagination

We highly recommend paginating your results. Call the paginate method before the search method, and you'll get an instance of \Illuminate\Contracts\Pagination\LengthAwarePaginator as a result. The paginate method takes three (optional) parameters to customize the paginator. These arguments are the same as Laravel's database paginator.

Search::add(Post::class, 'title') ->add(Video::class, 'title') ->paginate() // or ->paginate($perPage = 15, $pageName = 'page', $page = 1) ->search('build');

You may also use simple pagination. This will return an instance of \Illuminate\Contracts\Pagination\Paginator, which is not length aware:

Search::add(Post::class, 'title') ->add(Video::class, 'title') ->simplePaginate() // or ->simplePaginate($perPage = 15, $pageName = 'page', $page = 1) ->search('build');

Constraints and scoped queries

Instead of the class name, you can also pass an instance of the Eloquent query builder to the add method. This allows you to add constraints to each model.

Search::add(Post::published(), 'title') ->add(Video::where('views', '>', 2500), 'title') ->search('compile');

Multiple columns per model

You can search through multiple columns by passing an array of columns as the second argument.

Search::add(Post::class, ['title', 'body']) ->add(Video::class, ['title', 'subtitle']) ->search('eloquent');

Search through (nested) relationships

You can search through (nested) relationships by using the dot notation:

Search::add(Post::class, ['comments.body']) ->add(Video::class, ['posts.user.biography']) ->search('solution');

Full-Text Search

You may use MySQL's Full-Text Search by using the addFullText method. You can search through a single or multiple columns (using full text indexes), and you can specify a set of options, for example, to specify the mode. You can even mix regular and full-text searches in one query:

Search::new() ->add(Post::class, 'title') ->addFullText(Video::class, 'title', ['mode' => 'boolean']) ->addFullText(Blog::class, ['title', 'subtitle', 'body'], ['mode' => 'boolean']) ->search('framework -css');

If you want to search through relationships, you need to pass in an array where the array key contains the relation, while the value is an array of columns:

Search::new() ->addFullText(Page::class, [ 'posts' => ['title', 'body'], 'sections' => ['title', 'subtitle', 'body'], ]) ->search('framework -css');

Sounds like

MySQL has a soundex algorithm built-in so you can search for terms that sound almost the same. You can use this feature by calling the soundsLike method:

Search::new() ->add(Post::class, 'framework') ->add(Video::class, 'framework') ->soundsLike() ->search('larafel');

Eager load relationships

Not much to explain here, but this is supported as well :)

Search::add(Post::with('comments'), 'title') ->add(Video::with('likes'), 'title') ->search('guitar');

Getting results without searching

You call the search method without a term or with an empty term. In this case, you can discard the second argument of the add method. With the orderBy method, you can set the column to sort by (previously the third argument):

Search::add(Post::class) ->orderBy('published_at') ->add(Video::class) ->orderBy('released_at') ->search();

Counting records

You can count the number of results with the count method:

Search::add(Post::published(), 'title') ->add(Video::where('views', '>', 2500), 'title') ->count('compile');

Model Identifier

You can use the includeModelType to add the model type to the search result.

Search::add(Post::class, 'title') ->add(Video::class, 'title') ->includeModelType() ->paginate() ->search('foo'); // Example result with model identifier. { "current_page": 1, "data": [ { "id": 1, "video_id": null, "title": "foo", "published_at": null, "created_at": "2021-12-03T09:39:10.000000Z", "updated_at": "2021-12-03T09:39:10.000000Z", "type": "Post", }, { "id": 1, "title": "foo", "subtitle": null, "published_at": null, "created_at": "2021-12-03T09:39:10.000000Z", "updated_at": "2021-12-03T09:39:10.000000Z", "type": "Video", }, ], ... }

By default, it uses the type key, but you can customize this by passing the key to the method.

You can also customize the type value by adding a public method searchType() to your model to override the default class base name.

class Video extends Model { public function searchType() { return 'awesome_video'; } } // Example result with searchType() method. { "current_page": 1, "data": [ { "id": 1, "video_id": null, "title": "foo", "published_at": null, "created_at": "2021-12-03T09:39:10.000000Z", "updated_at": "2021-12-03T09:39:10.000000Z", "type": "awesome_video", } ], ...

Standalone parser

You can use the parser with the parseTerms method:

$terms = Search::parseTerms('drums guitar');

You can also pass in a callback as a second argument to loop through each term:

Search::parseTerms('drums guitar', function($term, $key) { // });

Testing

composer test

Changelog

Please see CHANGELOG for more information about what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Other Laravel packages

  • Inertia Table: The Ultimate Table for Inertia.js with built-in Query Builder.
  • Laravel Blade On Demand: Laravel package to compile Blade templates in memory.
  • Laravel Eloquent Scope as Select: Stop duplicating your Eloquent query scopes and constraints in PHP. This package lets you re-use your query scopes and constraints by adding them as a subquery.
  • Laravel FFMpeg: This package provides an integration with FFmpeg for Laravel. The storage of the files is handled by Laravel's Filesystem.
  • Laravel MinIO Testing Tools: Run your tests against a MinIO S3 server.
  • Laravel Mixins: A collection of Laravel goodies.
  • Laravel Paddle: Paddle.com API integration for Laravel with support for webhooks/events.
  • Laravel Task Runner: Write Shell scripts like Blade Components and run them locally or on a remote server.
  • Laravel Verify New Email: This package adds support for verifying new email addresses: when a user updates its email address, it won't replace the old one until the new one is verified.
  • Laravel XSS Protection: Laravel Middleware to protect your app

编辑推荐精选

Trae

Trae

字节跳动发布的AI编程神器IDE

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

热门AI工具生产力协作转型TraeAI IDE
蛙蛙写作

蛙蛙写作

AI小说写作助手,一站式润色、改写、扩写

蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。

AI助手AI工具AI写作工具AI辅助写作蛙蛙写作学术助手办公助手营销助手
问小白

问小白

全能AI智能助手,随时解答生活与工作的多样问题

问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。

聊天机器人AI助手热门AI工具AI对话
Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

热门AI工具AI办公办公工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图
讯��飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

模型训练热门AI工具内容创作智能问答AI开发讯飞星火大模型多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

咔片PPT

咔片PPT

AI助力,做PPT更简单!

咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

AI助手热门AI工具AI创作AI辅助写作讯飞绘文内容运营个性化文章多平台分发
材料星

材料星

专业的AI公文写作平台,公文写作神器

AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

下拉加载更多