PHPackages                             webikevn/laravel-fulltext-search - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Search &amp; Filtering](/categories/search)
4. /
5. webikevn/laravel-fulltext-search

ActiveLibrary[Search &amp; Filtering](/categories/search)

webikevn/laravel-fulltext-search
================================

Full-text search and reusable queries in laravel.

1.0.3(5y ago)016MITPHPPHP &gt;=7.3.0

Since Sep 1Pushed 5y ago1 watchersCompare

[ Source](https://github.com/webikevn/laravel-fulltext-search)[ Packagist](https://packagist.org/packages/webikevn/laravel-fulltext-search)[ RSS](/packages/webikevn-laravel-fulltext-search/feed)WikiDiscussions master Synced 2d ago

READMEChangelog (4)Dependencies (1)Versions (5)Used By (0)

Searchable
==========

[](#searchable)

Full-text search and reusable queries in laravel.

- Currently supports MySQL only.
- Helpful for complex table queries with multiple joins and derived columns.
- Reusable queries and column definitions.

Overview
--------

[](#overview)

### Full-text search on eloquent models

[](#full-text-search-on-eloquent-models)

Simple setup for searchable model and can search on derived columns.

```
use Webike\Searchable\Searchable;

class Post
{
    use Searchable;

    protected $searchable = [
        // This will search on the defined searchable columns
        'columns' => [
            'posts.title',
            'posts.body',
            'author_full_name' => 'CONCAT(authors.first_name, " ", authors.last_name)'
        ],
        'joins' => [
            'authors' => ['authors.id', 'posts.author_id']
        ]
    ];

    public function author()
    {
        return $this->belongsTo(Author::class);
    }
}

// Usage
Post::search("Some title or body content or even the author's full name")
    ->with('author')
    ->paginate();
```

Imagine we have an api for a table or list that has full-text searching and column sorting and pagination. This is a usual setup for a table or list. The internal explanations will be available on the documentation below. Our api call may look like this:

`http://awesome-app.com/api/posts?per_page=10&page=1&sort_by=title&descending=true&search=SomePostTitle`

Your code can look like this:

```
class PostsController
{
    public function index()
    {
        return Post::sortByRelevance(!request()->bool('sort_by'))
            ->search(request('search'))
            ->when(Post::isColumnValid($sortColumn = request('sort_by')), function ($query) use ($sortColumn) {
                $query->orderBy(
                    \DB::raw(
                        (new Post)->getSortableColumn($sortColumn) ?? // valid sortable column
                        (new Post)->searchQuery()->getColumn($sortColumn) ?? // valid search column
                        $sortColumn // valid original table column
                    ),
                    request()->bool('descending') ? 'desc' : 'asc'
                );
            })
            ->paginate();
    }

}
```

Documentation
-------------

[](#documentation)

### Installation

[](#installation)

```
composer require webikevn/laravel-fulltext-search

```

### Searchable Model

[](#searchable-model)

```
use Webike\Searchable\Searchable;

class Post extends Model
{
    use Searchable;

    /**
     * Searchable model definitions.
     */
     protected $searchable = [
        // Searchable columns of the model.
        // If this is not defined it will default to all table columns.
        'columns' => [
            'posts.title',
            'posts.body',
            'author_full_name' => 'CONCAT(authors.first_name, " ", authors.last_name)'
        ],
        // This is needed if there is a need to join other tables for derived columns.
        'joins' => [
            'authors' => ['authors.id', 'posts.author_id'], // defaults to leftJoin method of eloquent builder
            'another_table' => ['another_table.id', 'authors.another_table_id', 'join'], // can pass leftJoin, rightJoin, join of eloquent builder.
        ]
    ];

    /**
     * Can also be written like this for searchable columns.
     *
     * @var array
     */
    protected $searchableColumns = [
        'title',
        'body',
        'author_full_name' => 'CONCAT(authors.first_name, " ", authors.last_name)'
    ];

    /**
     * Can also be written like this for searchable joins.
     *
     * @var array
     */
    protected $searchableJoins = [
        'authors' => ['authors.id', 'posts.author_id']
    ];
}

// Usage
// Call search anywhere
// This only search on the defined columns.
Post::search('Some post')->paginate();
Post::where('likes', '>', 100)->search('Some post')->paginate();
```

This will addSelect field `sort_index` which will used to order or sort by relevance. If you want to disable sort by relevance, call method `sortByRelevance(false)` before `search()` method. Example:

```
Post::sortByRelevance(false)->search('Some post')->paginate();
Post::sortByRelevance(false)->where('likes', '>', 100)->search('Some post')->paginate();

```

### Set searchable configurations on runtime.

[](#set-searchable-configurations-on-runtime)

```
$post = new Post;
$post->setSearchable([ // addSearchable() method is also available
    'columns' => [
        'posts.title',
        'posts.body',
    ],
    'joins' => [
        'authors' => ['authors.id', 'posts.author_id']
    ]
]);
// or
$post->setSearchableColumns([ // addSearchableColumns() method is also available
    'posts.title',
    'posts.body',
]);
$post->setSearchableJoins([ // addSearchableJoins() method is also available
    'authors' => ['authors.id', 'posts.author_id']
]);
```

### Easy Sortable Columns

[](#easy-sortable-columns)

You can define columns to be only sortable but not be part of search query constraint. Just put it under `sortable_columns` as shown below . This column can be easily access to put in `orderBy` of query builder. All searchable columns are also sortable columns.

```
class Post {
     protected $searchable = [
        'columns' => [
            'title' => 'posts.title',
        ],
        'sortable_columns' => [
            'status_name' => 'statuses.name',
        ],
        'joins' => [
            'statuses' => ['statuses.id', 'posts.status_id']
        ]
    ];
}

// Usage

Post::search('A post title')->orderBy(Post::getSortableColumn('status_name'));
// This will only perform search on `posts`.`title` column and it will append "order by `statuses`.`name`" in the query.
// This is beneficial if your column is mapped to a different column name coming from front-end request.
```

### Custom Search Query - Exact Search Example

[](#custom-search-query---exact-search-example)

You can extend the class `Webike\Searchable\Search\SublimeSearch` a.k.a fuzzy-search implementation.

```
namespace App;

use Webike\Searchable\Search\SublimeSearch;

class ExactSearch extends SublimeSearch
{
    /**
     * {@inheritDoc}
     */
    protected function parseSearchStr($searchStr)
    {
        return $searchStr; // produces "where `column` like '{$searchStr}'"
        // or
        return "%{$searchStr}%"; // produces "where `column` like '%{$searchStr}%'"
    }
}
```

then use it in the model:

```
namespace App;

class User extends Model
{
    public function defaultSearchQuery()
    {
        return new ExactSearch($this, $this->searchableColumns(), $this->sortByRelevance, 'where');
    }
}
```

You may also check the build query by dd-ing it:

```
$query = User::search('John Doe');
dd($query->toSql());
```

which may output to

```
select * from users where `column` like 'John Doe'
// or
select * from users where `column` like '%John Doe%'

```

### Using derived columns for order by and where conditions

[](#using-derived-columns-for-order-by-and-where-conditions)

Usually we have queries that has a derived columns like our example for `Post`'s `author_full_name`. Sometimes we need to sort our query results by this column.

```
Post::search('Some search')->orderBy(Post::searchQuery()->author_full_name, 'desc')->paginate();
Post::search('Some search')->where(Post::searchQuery()->author_full_name, 'William%')->paginate();
```

Helper methods available on model
---------------------------------

[](#helper-methods-available-on-model)

### isColumnValid \[static\]

[](#iscolumnvalid-static)

- Identifies if the column is a valid column, either a regular table column or derived column.
- Useful for checking valid columns to avoid sql injection especially in `orderBy` query.

```
Post::isColumnValid(request('sort_by'));
```

### getTableColumns \[static\]

[](#gettablecolumns-static)

- Get the table columns.

```
Post::getTableColumns();
```

### enableSearchable

[](#enablesearchable)

- Enable the searchable behavior.

```
$query->getModel()->enableSearchable();
$query->search('foo');
```

### disableSearchable

[](#disablesearchable)

- Disable the searchable behavior.
- Calling `search()` method will not perform a search.

```
$query->getModel()->disableSearchable();
$query->search('foo');
```

### setSearchable

[](#setsearchable)

- Set or override the model's `$searchable` property.
- Useful for building searchable config on runtime.

```
$query->getModel()->setSearchable([
  'columns' => ['title', 'status'],
  'joins' => [...],
]);
$query->search('foo');
```

### addSearchable

[](#addsearchable)

- Add columns or joins in the model's `$searchable` property.
- Useful for building searchable config on runtime.

```
$query->getModel()->addSearchable([
  'columns' => ['title', 'status'],
  'joins' => [...],
]);
$query->search('foo');
```

Warning
-------

[](#warning)

Calling `select()` after `search()` will overwrite `sort_index` field, so it is recommended to call `select()`before `search()`.

Credits
-------

[](#credits)

- Ray Anthony Madrona [@raymadrona](https://github.com/raymadrona), for the tips on using MySQL `LOCATE()` for sort relevance.
- [nicolaslopezj/searchable](https://github.com/nicolaslopezj/searchable), for the `$searchable` property declaration style.

###  Health Score

23

—

LowBetter than 27% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

4

Last Release

2079d ago

PHP version history (2 changes)1.0.0PHP &gt;=7.1.3

1.0.2PHP &gt;=7.3.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/09f7d0bae763e995aa8b55c06da4a631819fc5e7acf10f1aa4a17e1ea8ab0fd8?d=identicon)[giangbeoit](/maintainers/giangbeoit)

---

Top Contributors

[![GiangBeo](https://avatars.githubusercontent.com/u/3804842?v=4)](https://github.com/GiangBeo "GiangBeo (5 commits)")

---

Tags

laravellaravel-packagequerygridquery builderfull text searcheloquent-search

### Embed Badge

![Health badge](/badges/webikevn-laravel-fulltext-search/health.svg)

```
[![Health](https://phpackages.com/badges/webikevn-laravel-fulltext-search/health.svg)](https://phpackages.com/packages/webikevn-laravel-fulltext-search)
```

###  Alternatives

[ajcastro/searchable

Pattern-matching search for Laravel eloquent models.

2847.7k](/packages/ajcastro-searchable)[devnoiseconsulting/laravel-scout-postgres-tsvector

PostgreSQL Full Text Search Driver for Laravel Scout

58110.1k](/packages/devnoiseconsulting-laravel-scout-postgres-tsvector)[ambengers/query-filter

Laravel package for filtering resources with request query string

3513.5k](/packages/ambengers-query-filter)[omaressaouaf/query-builder-criteria

Define reusable query criteria for filtering, sorting, search, field selection, and includes in Laravel Eloquent models

282.4k](/packages/omaressaouaf-query-builder-criteria)[hashemi/queryfilter

A simple &amp; dynamic package for your eloquent query in laravel. It will help you to write query logic individual for each parameter.

391.1k](/packages/hashemi-queryfilter)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
