Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
L

laravel-cross-eloquent-search

> 后端框架
Open source

Laravel package to search through multiple Eloquent models. Supports sorting, pagination, scoped queries, eager load relationships and searching through single

1.1K stars0 likes0 views
WebsiteGitHub

About

Laravel package to search through multiple Eloquent models. Supports sorting, pagination, scoped queries, eager load relationships and searching through single

Laravel Cross Eloquent Search

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

❤️ 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+, PostgreSQL 12+, or SQLite 3.8+
  • Laravel 11.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.
  • Works with MySQL, PostgreSQL, and SQLite.
  • Zero third-party dependencies.

Driver Compatibility: Features like Full-Text Search and SOUNDS LIKE use database-specific implementations. MySQL uses native full-text indexes, PostgreSQL uses tsquery (requiring the pg_trgm extension for similarity search), and SQLite uses LIKE-based alternatives. The package automatically detects your connection and uses the appropriate strategy.

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:

bash
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.

php
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:

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

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

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

In addition, you can use the tap method to tap into the searcher instance:

php
Search::add(Post::class, 'title')
    ->add(Video::class, 'title')
    ->tap(function ($searcher) {
        Log::info('Search configuration', ['models' => $searcher->getModelsToSearchThrough()]);
    })
    ->search('laravel');

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%.

php
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:

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

Exact Match

If you want to perform exact matching without any wildcards, you can use the exactMatch method. This disables both beginning and ending wildcards and uses the exact equality operator (=) instead of the LIKE operator:

php
Search::add(Post::class, 'title')
    ->add(Video::class, 'title')
    ->exactMatch()
    ->search('Laravel');

In this example, only records with the exact title "Laravel" will be returned, not titles containing "Laravel" as a substring.

Multi-word search

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

php
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.

php
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.

php
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.

php
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:

php
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.

php
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:

php
Search::add(Post::class, 'title')
    ->add(Video::class, 'title')

    ->simplePaginate()
    // or
    ->simplePaginate($perPage = 15, $pageName = 'page', $page = 1)

    ->search('build');

Query String Parameters

To retain query string parameters in pagination links, use the withQueryString method. Without arguments, it uses the current request's query string:

php
Search::add(Post::class, 'title')
    ->add(Video::class, 'title')
    ->paginate(15)
    ->withQueryString()  // Uses request()->query()
    ->search('build');

Or pass a custom array of parameters:

php
Search::add(Post::class, 'title')
    ->add(Video::class, 'title')
    ->paginate(15)
    ->withQueryString(['filter' => 'active', 'sort' => 'date'])
    ->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.

php
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.

php
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:

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

Full-Text Search

You can use the addFullText method to search using your database's native full-text search capabilities:

php
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:

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

Sounds like

Search for terms that sound similar using the soundsLike method:

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

Eager load relationships

Eager loading relationships is fully supported

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHPlaravellaravel-packagemysqlphp

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架