bhavishyajeet/laravel-searchable-trait
Composer 安装命令:
composer require bhavishyajeet/laravel-searchable-trait
包简介
A powerful, flexible search trait for Laravel Eloquent models with support for relation searches, custom column selection, and configurable table mappings.
README 文档
README
A powerful, flexible search trait for Laravel Eloquent models with support for relation searches, custom column selection, and configurable table mappings.
Features
- 🔍 Powerful Search: Search across multiple columns and relations
- 🔧 Highly Configurable: Customize table mappings, foreign keys, and join conditions
- 🛡️ Security First: Built-in column validation and SQL injection protection
- ⚡ Performance Optimized: Efficient joins with duplicate prevention
- 🎯 Flexible: Support for quoted phrases, multiple search terms, and custom sorting
- 📱 API Ready: Perfect for frontend search implementations
Installation
Via Private Repository
Add your private repository to your composer.json:
{
"repositories": [
{
"type": "vcs",
"url": "https://github.com/your-username/laravel-searchable-trait.git"
}
]
}
Then install the package:
composer require bhavishyajeet/laravel-searchable-trait
Laravel Auto-Discovery
The package will automatically register its service provider. If you need to register it manually, add to config/app.php:
'providers' => [ // ... Bhavishyajeet\LaravelSearchableTrait\SearchableTraitServiceProvider::class, ],
Publish Configuration (Optional)
php artisan vendor:publish --tag=searchable-config
Quick Start
Basic Usage
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Bhavishyajeet\LaravelSearchableTrait\Traits\Searchable; class User extends Model { use Searchable; protected $searchable_columns = ['name', 'email']; protected $return_from_search = ['id', 'name', 'email']; protected $allowed_search_columns = ['name', 'email', 'phone']; } // Search usage $results = User::search('john')->get(); $results = User::search('john', ['name', 'email'])->get();
With Relations
class Application extends Model { use Searchable; protected $searchable_columns = [ 'status', 'career.posting_title', 'candidate.name', 'candidate.email', ]; protected $allowed_search_columns = [ 'status', 'career.posting_title', 'candidate.name', 'candidate.email', ]; // Custom table mappings protected $relation_table_map = [ 'career' => 'careers', ]; // Custom foreign key mappings protected $relation_foreign_key_map = [ 'career' => 'job_id', 'candidate' => 'candidate_id', ]; // Custom related key mappings protected $relation_related_key_map = [ 'career' => 'job_id', 'candidate' => 'candidate_id', ]; }
Configuration Properties
Core Properties
// Columns searched by default protected $searchable_columns = ['name', 'email']; // Columns returned from search protected $return_from_search = ['id', 'name', 'email']; // Columns frontend can request to search protected $allowed_search_columns = ['name', 'email', 'phone'];
Advanced Configuration
// Complete relation configurations protected $relation_configurations = [ 'department' => [ 'table' => 'departments', 'foreign_key' => 'dept_id', 'related_key' => 'id', 'join_type' => 'inner', ], ]; // Custom join conditions protected $custom_join_conditions = [ 'career' => [ ['column1' => 'jobs.status', 'operator' => '=', 'column2' => "'active'"], ], 'profile' => function ($join, $config, $model) { $join->where('user_profiles.is_active', '=', 1); }, ];
API Usage
Frontend Requests
# Basic search GET /api/v1/candidates?query=john # Custom column search GET /api/v1/candidates?query=john&search_columns[]=name&search_columns[]=email # Relation search GET /api/v1/applications?query=developer&search_columns[]=career.posting_title # Multiple terms GET /api/v1/candidates?query=john developer senior # Quoted phrases GET /api/v1/candidates?query="john doe"
Controller Implementation
class CandidateController extends ApiController { public function index(CandidateListingRequest $request) { $candidates = $this->candidate ->when($request->input('query'), function ($query) use ($request) { $searchColumns = $request->input('search_columns'); $query->search($request->input('query'), $searchColumns); }) ->paginate($this->getLimitPerPage()); return CandidateListResource::collection($candidates); } }
Request Validation
class CandidateListingRequest extends FormRequest { public function rules(): array { return [ 'query' => ['nullable', 'string'], 'search_columns' => ['sometimes', 'array'], 'search_columns.*' => ['sometimes', 'string'], ]; } }
Method Signature
public function scopeSearch( Builder $builder, string $needle, ?array $customSearchColumns = null, string $orderByColumn = 'id', string $orderByDirection = 'asc', ?string $sortOrder = null ): Builder
Security Features
- Column Validation - Only whitelisted columns can be searched
- SQL Injection Protection - All inputs properly escaped
- Automatic Filtering - Invalid columns silently ignored
- Resource Alignment - Search columns match API resource fields
Performance Features
- Efficient Joins - Left joins with duplicate prevention
- Smart Query Building - Proper parameterization and escaping
- Optimized Term Parsing - Support for quoted phrases
- Configurable Join Types - Inner/left joins for performance
Testing
Run the package tests:
composer test
Run tests with coverage:
composer test-coverage
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This package is open-sourced software licensed under the MIT license.
Support
For support, please contact reidlos2006@duck.com or create an issue in the repository.
bhavishyajeet/laravel-searchable-trait 适用场景与选型建议
bhavishyajeet/laravel-searchable-trait 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 4 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 07 月 26 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「database」 「search」 「query」 「trait」 「laravel」 「relations」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 bhavishyajeet/laravel-searchable-trait 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 bhavishyajeet/laravel-searchable-trait 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 bhavishyajeet/laravel-searchable-trait 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Dibi is Database Abstraction Library for PHP
A Laravel package to retrieve data from Google Search Console
Store your language lines in the database, yaml or other sources
Indexed Search Autocomplete - Extends the TYPO3 Core Extension Indexed_Search searchform with an autocomplete feature.
A package for automatically encrypting and decrypting Eloquent attributes in Laravel 5.5+, based on configuration settings.
Query filtering in your frontend
统计信息
- 总下载量: 4
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 11
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-07-26