A package that provides a search feature for Eloquent models. You can define SearchAspects for your Eloquent model that use different search techniques, such as an exact match or partial match.
It is heavily inspired by Spatie's Query Builder and can be used in conjunction with this package.
This package can be installed through Composer:
$ composer require testmonitor/eloquent-searchable
Next, publish the configuration file:
$ php artisan vendor:publish --tag=eloquent-searchable
The configuration file allows you the change the HTTP parameter name as well as the minimal query length.
To add searchable functionality to your Eloquent model, follow these steps:
- Use the trait
TestMonitor\Searchable\Searchable
in your model(s). - Include the searchUsing scope together with one or more SearchAspects.
Add the searchable trait on the models you want to make searchable:
use Illuminate\Database\Eloquent\Model;
use TestMonitor\Searchable\Searchable;
class User extends Model
{
use Searchable;
// ...
}
Next, include the searchUsing
scope with SearchAspects
to define your
search strategy:
use App\Models\User;
use Illuminate\Routing\Controller;
use TestMonitor\Searchable\Aspects\SearchAspect;
class UsersController extends Controller
{
public function index()
{
return User::query()
->seachUsing([
SearchAspect::exact('first_name'),
SearchAspect::exact('last_name'),
SearchAspect::partial('email'),
])
->get();
}
}
In this example, the controller provides a way to search through a set of users:
- Both the first and last names are searched using the “exact” strategy. Only exact matches will be returned.
- The email field is searched using the “partial” match strategy. When the query term occurs within the email address, it will be returned.
The search query is automatically derived from the HTTP request. You can
modify the HTTP query parameter in the configuration file. By default,
the name query
is used.
The package contains integration tests. You can run them using PHPUnit.
$ vendor/bin/phpunit
Refer to CHANGELOG for more information.
Refer to CONTRIBUTING for contributing details.
The MIT License (MIT). Refer to the License for more information.