PHPackages                             montesilva/laravel-search-sort - 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. [Database &amp; ORM](/categories/database)
4. /
5. montesilva/laravel-search-sort

ActiveLibrary[Database &amp; ORM](/categories/database)

montesilva/laravel-search-sort
==============================

Eloquent model search and sort trait.

1.0.4(4y ago)18MITPHPPHP &gt;=7.3

Since Oct 8Pushed 4y ago1 watchersCompare

[ Source](https://github.com/montesilva/laravel-search-sort)[ Packagist](https://packagist.org/packages/montesilva/laravel-search-sort)[ RSS](/packages/montesilva-laravel-search-sort/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (6)Dependencies (1)Versions (7)Used By (0)

LaravelSearchSort, a basic search and sort trait for Laravel 7 and 8
====================================================================

[](#laravelsearchsort-a-basic-search-and-sort-trait-for-laravel-7-and-8)

LaravelSearchSort is a fork from nicolaslopezj/searchable. It's a trait for Laravel 7+ that adds a simple search, sort function to Eloquent Models.

LaravelSearchSort allows you to perform searches in a table giving priorities to each field for the table and it's relations, and also sorting these results by given columns and directions.

This is not optimized for big searches, but sometimes you just need to make it simple (Although it is not slow).

Installation
============

[](#installation)

Simply add the package to your `composer.json` file and run `composer update`.

```
"montesilva/laravel-search-sort": "1.*"

```

You can also use this command:

```
composer require montesilva/laravel-search-sort

```

Laravel 8 Support
-----------------

[](#laravel-8-support)

For Laravel 8 `config/database.php` must be changed.

In `config/database.php`, set mysql's `'strict'` to `false`.

```
'mysql' => [
    ...
    'strict' => false,
    ...
],
```

Usage
=====

[](#usage)

Add the trait to your model and add your search and/or sort rules.

```
use Montesilva\LaravelSearchSort\SearchSortTrait;

class User extends \Eloquent
{
    use SearchSortTrait;

    /**
     * Searchable rules.
     *
     * @var array
     */
    protected $search_sort = [
        /**
         * Columns and their priority in search results.
         * Columns with higher values are more important.
         * Columns with equal values have equal importance.
         *
         * @var array
         */
        'search_columns' => [
            'users.first_name' => 10,
            'users.last_name' => 10,
            'users.bio' => 2,
            'users.email' => 5,
            'posts.title' => 2,
            'posts.body' => 1,
        ],
        'sort_columns' => [
            'users.first_name', 'users.last_name', 'posts.title', 'posts.email'
        ],
        'joins' => [
            'posts' => ['users.id','posts.user_id'],
        ],
        'groupBy' => [
            'posts.id'
        ]
    ];

    public function posts()
    {
        return $this->hasMany('Post');
    }

}
```

Search
------

[](#search)

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();
```

Sort
----

[](#sort)

Or you can sort your model.

```
// Sort array with sortable column and direction (asc, desc)
$sorts = [
    [
        'prop' => 'users.first_name',
        'dir' => 'asc'
    ]
];

// Simple sort
$users = User::sort($sorts)->get();

// Sort and get relations
// It will not get the relations if you don't do this
$users = User::sort($query)
            ->with('posts')
            ->get();
```

Search Paginated
----------------

[](#search-paginated)

As easy as laravel default queries

```
// Search with relations and paginate
$users = User::search($query)
            ->with('posts')
            ->paginate(20);
```

Sort Paginated
--------------

[](#sort-paginated)

```
// Sort array with sortable column and direction (asc, desc)
$sorts = [
    [
        'prop' => 'users.first_name',
        'dir' => 'asc'
    ]
];

// Search with relations and paginate
$users = User::sort($sorts)
            ->with('posts')
            ->paginate(20);
```

Search and Sort
---------------

[](#search-and-sort)

You can also search and sort at the same time

```
// Sort array with sortable column and direction (asc, desc)
$sorts = [
    [
        'prop' => 'users.first_name',
        'dir' => 'asc'
    ]
];

// Search and sort with relations and paginate
$users = User::searchSort($query, $sorts)
            ->with('posts')
            ->paginate(20);
```

Mix queries
-----------

[](#mix-queries)

Search and Sort methods are compatible with any eloquent method. You can do things like this:

```
// Search only active users
$users = User::where('status', 'active')
            ->search($query)
            ->paginate(20);
```

Mix queries with joins before search and sort
---------------------------------------------

[](#mix-queries-with-joins-before-search-and-sort)

You can join other tables first to have the join tables available to include them in any eloquent method

```
// Add joins first
$builder = User::addJoins()->where('posts.title', 'Test');
// Search and sort without making joins in scope
$users = $builder::searchSort($query, $sorts, false)
            ->paginate(20);
```

```
// Search or sort without making joins in search or sort scope
$users = User::addJoins()
                ->where('posts.title', 'Test')
                ->search($query, false)
                ->sort($sorts, false)
                ->with('posts')
                ->paginate(20);
```

Custom Threshold
----------------

[](#custom-threshold)

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, true, 0)
            ->paginate(20);
```

The above, will return all users in order of relevance.

Entire Text search
------------------

[](#entire-text-search)

By default, multi-word search terms are split and LaravelSearchSort 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, 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, true)->get();
```

Entire Text search sorted
-------------------------

[](#entire-text-search-sorted)

```
// Do not include matches that only matched "John" OR "Doe".
$users = User::searchSort("John Doe", $sorts, null, true, true, true)->get();
```

Contributing
------------

[](#contributing)

Anyone is welcome to contribute. Fork, make your changes, and then submit a pull request.

###  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

Maturity49

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

6

Last Release

1678d ago

Major Versions

0.1.9 → 1.0.02021-10-08

### Community

Maintainers

![](https://www.gravatar.com/avatar/533fb7ba4ea787d62d77c34f9c98e457fbfbe3b04355d910f1d604671158f7d9?d=identicon)[montesilva](/maintainers/montesilva)

---

Top Contributors

[![montesilva](https://avatars.githubusercontent.com/u/92026259?v=4)](https://github.com/montesilva "montesilva (2 commits)")

---

Tags

eloquenteloquent-modelslaravellaravel-frameworklaravel8phpprioritizing-matchessearchsearchablesortsortablesearchlaraveldatabasemodeleloquentsortablesortsearchable

### Embed Badge

![Health badge](/badges/montesilva-laravel-search-sort/health.svg)

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

###  Alternatives

[nicolaslopezj/searchable

Eloquent model search trait.

2.0k2.7M35](/packages/nicolaslopezj-searchable)[jedrzej/pimpable

Laravel 4/5/6 package that allows to dynamically filter, sort and eager load relations for your models using request parameters

105179.0k1](/packages/jedrzej-pimpable)

PHPackages © 2026

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