A php trait to search laravel models
Searchable is a trait for Laravel 4.2+ and Laravel 5.0 that adds a simple search function to Eloquent Models.
Searchable allows you to perform searches in a table giving priorities to each field for the table and it's relations.
This is not optimized for big searches, but sometimes you just need to make it simple (Although it is not slow).
Simply add the package to your composer.json file and run composer update.
"nicolaslopezj/searchable": "1.*"Add the trait to your model and your search rules.
…Now you can search your model.
// Simple search
$users = User::search($query)->get();
// Search and get relations
// It will not get the relations if you don't do this
$users = User::search($query)
->with('posts')
->get();As easy as laravel default queries
// Search with relations and paginate
$users = User::search($query)
->with('posts')
->paginate(20);Search method is compatible with any eloquent method. You can do things like this:
// Search only active users
$users = User::where('status', 'active')
->search($query)
->paginate(20);The default threshold for accepted relevance is the sum of all attribute relevance divided by 4. To change this value you can pass in a second parameter to search() like so:
// Search with lower relevance threshold
$users = User::where('status', 'active')
->search($query, 0)
->paginate(20);The above, will return all users in order of relevance.
By default, multi-word search terms are split and Searchable searches for each word individually. Relevance plays a role in prioritizing matches that matched on multiple words. If you want to prioritize matches that include the multi-word search (thus, without splitting into words) you can enable full text search by setting the third value to true. Example:
// Prioritize matches containing "John Doe" above matches containing only "John" or "Doe".
$users = User::search("John Doe", null, true)->get();If you explicitly want to search for full text matches only, you can disable multi-word splitting by setting the fourth parameter to true.
// Do not include matches that only matched "John" OR "Doe".
$users = User::search("John Doe", null, true, true)->get();Searchable builds a query that search through your model using Laravel's Eloquent. Here is an example query
use Nicolaslopezj\Searchable\SearchableTrait;
class User extends \Eloquent
{
use SearchableTrait;
/**
* Searchable rules.
*
* @var array
*/
protected $searchable = [
'columns' => [
'first_name' => 10,
'last_name' => 10,
'bio' => 2,
'email' => 5,
],
];
}$search = User::search('Sed neque labore', null, true)->get();…Anyone is welcome to contribute. Fork, make your changes, and then submit a pull request.
No open issues yet, or sync has not completed.