An Eloquent scope for building a search query using LIKE statements
baethon/eloquent-searchable-scope is a Laravel package for an eloquent scope for building a search query using like statements.
It currently has 0 GitHub stars and 1.949 downloads on Packagist (latest version v2.0.1).
Install it with composer require baethon/eloquent-searchable-scope.
Discover more Laravel packages by baethon
or browse all Laravel packages to compare alternatives.
Last updated
A dead-simple Eloquent scope that builds a search query using LIKE statements. Supports searching using relations.
$foundPosts = Post::query()
->search($search)
->get();
composer require baethon/eloquent-searchable-scope
Import Searchable trait and use it in model:
<?php
namespace App\Models;
use Baethon\Laravel\Scopes\Searchable;
class Post extends Model
{
use Searchable;
}
Then, define the list of fields that should be used for searching.
<?php
namespace App\Models;
use Baethon\Laravel\Scopes\Searchable;
class Post extends Model
{
use Searchable;
protected $searchable = ['topic', 'text', 'user.email'];
}
Note: user.email refers to user relation that has to be defined in the model.
By default, the scope will use the full search term in the query. To break the search term to words, you'll have to define $searchOptions property:
<?php
namespace App\Models;
use Baethon\Laravel\Scopes\Searchable;
use Baethon\Laravel\Scopes\SearchableOptions;
class Post extends Model
{
use Searchable;
protected $searchable = ['topic', 'text', 'user.email'];
protected $searchOptions = SearchableOptions::BREAK_WORDS;
}
Note: the scope will use only words with length >= 3.
It's possible to define the searchable fields when calling search() scope:
$foundPosts = Post::query()
->search($search, [
'title',
])
->get();
This scope has been discussed in 🔗 other 🔗 places.
Every time I had to find them, so I decided to make a package that will be easy to install.
I didn't discover anything new here!
composer test