bhavishyajeet/laravel-searchable-trait
最新稳定版本:v1.0.0
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.
统计信息
- 总下载量: 3
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 1
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-07-26