PHPackages                             usermp/laravel-filter - 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. usermp/laravel-filter

ActiveLibrary

usermp/laravel-filter
=====================

A Laravel package for filterable traits

v2.0.0(11mo ago)4197↓100%1[1 PRs](https://github.com/usermp/laravel-filter/pulls)MITPHPPHP ^8.0|^8.1|^8.2|^8.3

Since May 31Pushed 11mo ago1 watchersCompare

[ Source](https://github.com/usermp/laravel-filter)[ Packagist](https://packagist.org/packages/usermp/laravel-filter)[ RSS](/packages/usermp-laravel-filter/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (2)Dependencies (1)Versions (3)Used By (0)

Laravel Filterable
==================

[](#laravel-filterable)

[![usermp-laravel-filterable](https://camo.githubusercontent.com/4707fd8021a57f28271c79250fd39f8ff3633b1ceb2c73ca8e3da0c14be80e90/68747470733a2f2f62616e6e6572732e6265796f6e64636f2e64652f4c61726176656c25323046696c74657261626c652e706e673f7468656d653d6c69676874267061636b6167654d616e616765723d636f6d706f7365722b72657175697265267061636b6167654e616d653d757365726d702532466c61726176656c2d66696c746572267061747465726e3d62616e6b4e6f7465267374796c653d7374796c655f31266465736372697074696f6e3d5468652b46696c74657261626c652b74726169742b69732b64657369676e65642b746f2b62652b757365642b77697468696e2b456c6f7175656e742b6d6f64656c732b696e2b612b4c61726176656c2b6170706c69636174696f6e2e266d643d312673686f7757617465726d61726b3d3026666f6e7453697a653d313030707826696d616765733d68747470732533412532462532466c61726176656c2e636f6d253246696d672532466c6f676f6d61726b2e6d696e2e737667)](https://camo.githubusercontent.com/4707fd8021a57f28271c79250fd39f8ff3633b1ceb2c73ca8e3da0c14be80e90/68747470733a2f2f62616e6e6572732e6265796f6e64636f2e64652f4c61726176656c25323046696c74657261626c652e706e673f7468656d653d6c69676874267061636b6167654d616e616765723d636f6d706f7365722b72657175697265267061636b6167654e616d653d757365726d702532466c61726176656c2d66696c746572267061747465726e3d62616e6b4e6f7465267374796c653d7374796c655f31266465736372697074696f6e3d5468652b46696c74657261626c652b74726169742b69732b64657369676e65642b746f2b62652b757365642b77697468696e2b456c6f7175656e742b6d6f64656c732b696e2b612b4c61726176656c2b6170706c69636174696f6e2e266d643d312673686f7757617465726d61726b3d3026666f6e7453697a653d313030707826696d616765733d68747470732533412532462532466c61726176656c2e636f6d253246696d672532466c6f676f6d61726b2e6d696e2e737667)

Overview
--------

[](#overview)

The `Filterable` trait is designed to be used within Eloquent models in a Laravel application. It provides a convenient way to apply filters to Eloquent queries based on HTTP request parameters. This trait supports filtering by model attributes as well as by attributes of related models, using various operators.

Installation
------------

[](#installation)

1. **Add the package to your project using Composer:**

    ```
    composer require usermp/laravel-filter
    ```
2. **Add the `Filterable` trait to your Eloquent model:**

    ```
    namespace App\Models;

    use Illuminate\Database\Eloquent\Model;
    use Usermp\LaravelFilter\Traits\Filterable; // Correct path to the Trait

    class YourModel extends Model
    {
        use Filterable;

        // (Optional) Override the main request key containing the filters.
        // protected string $filterRequestKeyOverride = 'my_filters'; // Defaults to 'filter'

        // Attributes of this model that can be filtered
        protected $filterable = [
            'attribute1',
            'attribute2',
            'status',
            'created_at',
            // Add other filterable attributes
        ];

        // Names of relations whose attributes can be filtered
        protected $filterableRelations = [
            'relation1', // Example: for filtering relation1.name
            'user',
            // Add other filterable relations
        ];
    }
    ```

Usage
-----

[](#usage)

To use the `Filterable` trait, call the `filter` scope on your model query and pass the `Illuminate\Http\Request` object. Filters should be passed in the query string under a main key, which defaults to `filter`.

**Example in a Controller:**

```
namespace App\Http\Controllers;

use App\Models\YourModel;
use Illuminate\Http\Request; // Inject the Request object

class YourModelController extends Controller
{
    public function index(Request $request)
    {
        $results = YourModel::query()
            ->filter($request) // Pass the entire Request object
            ->paginate();

        return response()->json($results);
    }
}
```

Examples
--------

[](#examples)

All filter parameters should be nested under a main key in the query string. The default key is `filter`.

### 1. Basic Attribute Filtering

[](#1-basic-attribute-filtering)

Assume the `Post` model has `title` and `status` in its `$filterable` array.

- **Filter by title (implicitly uses 'like'):**`GET /posts?filter[title]=Example Post`*(Finds posts where title contains "Example Post")*
- **Filter by status using 'equal' operator:**`GET /posts?filter[status][equal]=published`*(Finds posts where status is exactly "published")*
- **Filter by creation date using 'gte' (greater than or equal to):**`GET /posts?filter[created_at][gte]=2023-01-01`

### 2. Filtering by Related Model Attributes

[](#2-filtering-by-related-model-attributes)

Assume the `Post` model has `user` in `$filterableRelations` and the `User` model has a `name` attribute.

- **Filter posts by user's name (implicitly 'like'):**`GET /posts?filter[user.name]=John Doe`
- **Filter posts by user's email using 'equal':**`GET /posts?filter[user.email][equal]=john.doe@example.com`

### 3. Using Specific Operators

[](#3-using-specific-operators)

- **`in` operator (for multiple values):**Filter posts with status 'published' OR 'pending': `GET /posts?filter[status][in]=published,pending`Alternatively, using array syntax for the `in` values: `GET /posts?filter[status][in][]=published&filter[status][in][]=pending`

    Filter posts belonging to users with specific IDs: `GET /posts?filter[user.id][in]=1,5,10`
- **`between` operator (for ranges):**Filter posts created between two dates: `GET /posts?filter[created_at][between][]=2023-01-01&filter[created_at][between][]=2023-12-31`
- **`null` / `notnull` operators:**Filter posts where `published_at` is NULL: `GET /posts?filter[published_at][null]`

    Filter posts where `updated_at` is NOT NULL: `GET /posts?filter[updated_at][notnull]`

### 4. Customizing the Main Filter Key

[](#4-customizing-the-main-filter-key)

If you defined `$filterRequestKeyOverride = 'my_query_filters';` in your model:

`GET /posts?my_query_filters[title]=My%20Post`

Supported Operators
-------------------

[](#supported-operators)

The following operators can be used by specifying them as a key for the filter value:

OperatorQuery String ExampleDescription(none)`filter[title]=word`Default: `LIKE '%word%'` for string values.`equal``filter[status][equal]=active`Exact match (`=`).`notequal``filter[status][notequal]=archived`Not equal (`!=`).`gt``filter[views][gt]=100`Greater than (`>`).`gte``filter[views][gte]=100`Greater than or equal to (`>=`).`lt``filter[stock][lt]=10`Less than (`
