maestrodimateo/laravel-search 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

maestrodimateo/laravel-search

Composer 安装命令:

composer require maestrodimateo/laravel-search

包简介

Multi-criteria search trait for Laravel Eloquent models

README 文档

README

A Laravel package for simple and multi-column search on Eloquent models, with native support for JSON fields and PostgreSQL / MySQL dialects.

When to use this package

This package is a good fit when:

  • You store structured data as JSON columns — e.g. an apprenant column holding { "nom": "Dupont", "prenom": "Jean" }. Native Eloquent search does not handle JSON path extraction out of the box, and writing raw ->>'key' syntax every time is error-prone.
  • You need to search across multiple columns at once — instead of chaining multiple orWhere calls, you declare your columns once in getFullTextColumns() and call a single scope.
  • Your application targets both PostgreSQL and MySQL — the package transparently switches between ILIKE / ->> (PostgreSQL) and LIKE / ->>'$.path' (MySQL) with no change to your model code.
  • You want a lightweight solution with no external dependencies — no Elasticsearch, no Meilisearch, no extra infrastructure. Everything runs on your existing database.

This package is not the right choice when:

  • You need relevance ranking or full-text scoring (use PostgreSQL tsvector or a dedicated search engine instead).
  • Your tables have millions of rows and search performance is critical (consider adding a pg_trgm GIN index or delegating to a search engine).
  • You need fuzzy matching or typo tolerance (use Meilisearch or Algolia).

Requirements

  • PHP 8.3 or higher
  • Laravel 12.x
  • PostgreSQL or MySQL (SQLite supported for testing)

Installation

composer require maestrodimateo/laravel-search

The service provider is automatically discovered by Laravel.

Setup

1. Implement the Searchable contract

Add the WithSearch trait to your model and implement the Searchable interface to declare which columns are included in multi-column search.

use Illuminate\Database\Eloquent\Model;
use Maestrodimateo\Search\Contracts\Searchable;
use Maestrodimateo\Search\Traits\WithSearch;

class Article extends Model implements Searchable
{
    use WithSearch;

    protected $fillable = ['titre', 'auteur', 'meta'];

    protected $casts = ['meta' => 'array'];

    public function getFullTextColumns(): array
    {
        return ['titre', 'auteur', 'meta->ville'];
    }
}

Searchable is only required for fullTextSearch(). The search() method works without it.

Usage

Single-column search — search()

Performs a LIKE / ILIKE on one column.

// Search on a regular column
Article::search('titre', 'laravel')->get();

// Search on a JSON field
Article::search('meta->ville', 'paris')->get();

SQL generated (PostgreSQL):

SELECT * FROM articles WHERE titre ILIKE '%laravel%'
SELECT * FROM articles WHERE meta->>'ville' ILIKE '%paris%'

SQL generated (MySQL):

SELECT * FROM articles WHERE titre LIKE '%laravel%'
SELECT * FROM articles WHERE meta->>'$.ville' LIKE '%paris%'

Multi-column search — fullTextSearch()

Performs a LIKE / ILIKE across all columns declared in getFullTextColumns().

Article::fullTextSearch('dupont')->get();

SQL generated (PostgreSQL):

SELECT * FROM articles
WHERE CONCAT_WS('-', titre, auteur, meta->>'ville') ILIKE '%dupont%'

SQL generated (MySQL):

SELECT * FROM articles
WHERE CONCAT_WS('-', titre, auteur, meta->>'$.ville') LIKE '%dupont%'

Spaces in the search term are automatically converted to % for flexible matching:

Article::fullTextSearch('jean paris')->get();
// binding: %jean%paris%

Multi-word logic

The search string is tokenised into terms. By default every term must match (all), regardless of order:

Article::fullTextSearch('jean paris')->get();
// matches rows containing BOTH "jean" AND "paris", in any order
// bindings: ['%jean%', '%paris%']

Switch to "at least one term" matching with any:

Article::fullTextSearch('jean paris', 'any')->get();
// matches rows containing "jean" OR "paris"

Two operators are understood in the query string:

Article::fullTextSearch('"jean dupont"')->get();      // exact phrase, kept as one term
Article::fullTextSearch('laravel -wordpress')->get(); // exclude rows containing "wordpress"

Behaviour change (from 1.x): previously spaces were replaced by %, which forced word order and adjacency (jean paris%jean%paris%). Terms are now matched independently, so word order no longer matters.

Searching relations

Declare a column with a dot to search a related model. The last segment is the column, the rest is the relation path (resolved with whereHas()):

public function getFullTextColumns(): array
{
    return ['titre', 'author.name', 'comments.body'];
}

Article::fullTextSearch('dupont')->get();
// matches when "dupont" is in titre, OR the related author's name, OR a comment body

Relevance ordering

orderByRelevance() ranks results by how many searchable columns match. Pass the same term you searched for:

Article::fullTextSearch('dupont')->orderByRelevance('dupont')->get();
Article::fullTextSearch('dupont')->orderByRelevance('dupont', 'asc')->get();

Give columns different weights by returning an associative array from getFullTextColumns():

public function getFullTextColumns(): array
{
    return ['titre' => 3, 'auteur' => 1, 'meta->ville' => 1];
}

Only local columns contribute to the score; relation columns still filter via fullTextSearch() but are not ranked.

Chaining with other scopes

Both methods return a Builder and can be combined with any Eloquent scope:

Article::fullTextSearch('dupont')
    ->where('meta->ville', 'Paris')
    ->orderBy('created_at', 'desc')
    ->paginate(15);

JSON columns

The package automatically converts JSON paths to the correct SQL syntax for the current database driver.

Declaration syntax

Use -> notation in getFullTextColumns() or in search():

public function getFullTextColumns(): array
{
    return [
        'titre',          // regular column
        'auteur',         // regular column
        'meta->ville',    // JSON field
    ];
}

Conversion per dialect

Declaration PostgreSQL MySQL
titre titre titre
meta->ville meta->>'ville' meta->>'$.ville'
meta->addr->city meta->'addr'->>'city' meta->>'$.addr.city'

Supported dialects

The package automatically detects the driver configured in config/database.php.

Driver Operator JSON extraction
pgsql ILIKE ->> / ->'...'->>
mysql / others LIKE ->>'$.path'

Searchable contract

namespace Maestrodimateo\Search\Contracts;

interface Searchable
{
    /**
     * Columns used for multi-column full text search.
     * Supports JSON path notation with -> (e.g. "meta->ville").
     *
     * @return array<int, string>
     */
    public function getFullTextColumns(): array;
}

If fullTextSearch() is called on a model that does not implement Searchable, a LogicException is thrown:

Maestrodimateo\Search\Tests\Models\ArticleWithoutSearchable must implement
Maestrodimateo\Search\Contracts\Searchable to use fullTextSearch.

Testing

The package tests use Pest and Orchestra Testbench with an in-memory SQLite database.

cd packages/maestrodimateo/laravel-search
./vendor/bin/pest --compact

Method reference

search(string $attribute, ?string $search): Builder

Parameter Type Description
$attribute string Column or JSON path (column->key)
$search ?string Search term

fullTextSearch(?string $search, string $match = 'all'): Builder

Parameter Type Description
$search ?string Search string — split into terms, supports "phrases" and -exclusions
$match string 'all' (every term must match, default) or 'any' (at least one term)

Requires the model to implement Searchable.

orderByRelevance(?string $search, string $direction = 'desc'): Builder

Parameter Type Description
$search ?string Term to score against (usually the same passed to fullTextSearch)
$direction string 'desc' (default) or 'asc'; any other value falls back to 'desc'

Requires the model to implement Searchable. Only local columns are scored.

maestrodimateo/laravel-search 适用场景与选型建议

maestrodimateo/laravel-search 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 122 次下载、GitHub Stars 达 1, 最近一次更新时间为 2026 年 03 月 19 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「json」 「search」 「mysql」 「postgresql」 「laravel」 「eloquent」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 maestrodimateo/laravel-search 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 maestrodimateo/laravel-search 我们能提供哪些服务?
定制开发 / 二次开发

基于 maestrodimateo/laravel-search 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 122
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 14
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-03-19