A package to filter laravel model based on query params or retrieved model collection

Overview

Laravel Filterable

A package to filter laravel model based on query params or retrived model collection.

Installation

Require/Install the package using composer:

composer require touhidurabir/laravel-filterable

To publish the config file:

php artisan vendor:publish --provider="Touhidurabir\Filterable\FilterableServiceProvider" --tag=config

Configuration

The package comes with a configuration file named filterable that has to 2 important configs

Base Filter Class

This is a array that contains the base filter class for both the Query and Collection filter as :

'base_class' => [
    'query'         => \Touhidurabir\Filterable\Bases\BaseQueryFilter::class,
    'collection'    => \Touhidurabir\Filterable\Bases\BaseCollectionFilter::class,
],

If one need to even extend it to add more functionality or any custom feaure, can do it and set the base class in the config file .

Filter Class Namespace

This config define what would be the default namespace(and the store path) of the generated filter classes for the both the Query and Collection filter classes as :

'filterable_namespace' => [
    'query'         => 'App\\QueryFilters',
    'collection'    => 'App\\CollectionFilters',
],

If needed to, one can change the default path from there . but it is also possible to pass a different namespace to the filter generate command to provide a different namespace.

Command

This package includes a handly command to generate filter classes as

php artisan make:filter User

It will generate 2 class UserQueryFilter and UserCollectionFilter as per defined namespace in the config file .

This command also includes several handful options to make the filer class generation as flexiable as possible such as

--filters=

By passign comma separated filters, it will put those filters as filterable method in both the query and collection filter class as :

php artisan make:filter User --filter=name,email

For Query FIlter :

public function name($value) {

    // return $this->builder->;
}

public function email($value) {

    // return $this->builder->;
}

For Collection Filter :

public function name($item, $value) {

}

public function email($item, $value) {

}

--query-suffix=QueryFilter

Define what would be query filter class file name and class name suffix .

--collection-suffix=CollectionFilter

Define what would be collection filter class file name and class name suffix .

--no-suffix

If passed as switch option or flag, no suffix will be added to query or collection filter class names or files name.

--only-query

If passed as switch option or flag, will only generate the query filters and omit the collection filter class.

--only-collection

If passed as switch option or flag, will only generate the collection filters and omit the query filter class.

--replace

If passed as switch option or flag, will replace the existing file. By defalt if a given file already present, it will not replace it .

Usage

Generate the filters as

php artisan make:filter User --filter=name,email

it will generate UserQueryFilter.php and UserCollectionFilter.php class at the given path as :

<?php

namespace App\QueryFilters;

use Touhidurabir\Filterable\Bases\BaseQueryFilter;
use Illuminate\Database\Eloquent\Builder;

class UserQueryFilter extends BaseQueryFilter {

    /**
     * Retrieve the rules to validate filters value.
     * If a filter validation fails, the filter is not applied.
     *
     * @return array
     */
    protected function getRules() {
        
        return [];
    }

	
    /**
     * Filter by request param name
     *
     * @param  mixed $value
     * @return object<\Illuminate\Database\Eloquent\Builder>
     */
    public function name($value) {

        // return $this->builder->;
    }


    /**
     * Filter by request param email
     *
     * @param  mixed $value
     * @return object<\Illuminate\Database\Eloquent\Builder>
     */
    public function email($value) {

        // return $this->builder->;
    }


}
<?php

namespace App\CollectionFilters;

use Throwable;
use Touhidurabir\Filterable\Bases\BaseCollectionFilter;
use Illuminate\Support\Collection;

class UserCollectionFilter extends BaseCollectionFilter {

    /**
     * Retrieve the rules to validate filters value.
     * If a filter validation fails, the filter is not applied.
     *
     * @return array
     */
    protected function getRules() {
        
        return [];
    }

    
    /**
     * Filter by name
     *
     * @param  object $item
     * @param  mixed  $value
     *
     * @return
     */
    public function name($item, $value) {
        
        // return
    }


    /**
     * Filter by email
     *
     * @param  object $item
     * @param  mixed  $value
     *
     * @return
     */
    public function email($item, $value) {

        // return
    }
}

and the use the Filterable trait in the model as

use Touhidurabir\Filterable\Filterable;

class User extends Model {

    use Filterable;
}

The form some controller, use it as such

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\QueryFilters\UserQueryFilters;
use App\CollectionFilter\UserCollectionFilter;

class UserController extends Controller {

    public function index(Request $request) {

        $users = User::filter(new UserQueryFilter($request))->get();

        // or filter a collection as 

        $users = (new UserCollectionFilter)->filter(User::all(), ['email', 'name']);

        // of pass $request in constructor for collection filter

        $users = (new UserCollectionFilter($request))->filter(User::all());
    }
}

Also possible to use an existing array to pass as query to initiate the filter class as

UserQueryFilter::hydrate([]);
UserCollection::applyFilter(User::all() ,[]);

Note that it's not required to pass the $request as if not passed , it will resolve it from the Request Facade . Useful for case like when app running on laravel octane.

It can also handle the filter param validation as :

protected function getRules() {
    
    return [];
}

Set the validation rules there and those params that do not pass the validation will not be applied.

WHY a Collection Filter ?

It is a valid question why a collection filter as most of the time a query filter is sufficient. But some times a collection filter can be helpful to do some custom filter again after records are pull from DB. As this package allow to generate seperate collection filter, in those cases it can be helpful to such cause .

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

License

MIT

You might also like...
A laravel package to handle sanitize process of model data to create/update model records.

Laravel Model UUID A simple package to sanitize model data to create/update table records. Installation Require the package using composer: composer r

Laravel Nova filter for Spatie/laravel-tags

SpatieTagsNovaFilter This package allows you to filter resources by tags. (using the awesome Spatie/laravel-tags and Vue-MultiSelect ) Installation Fi

An Eloquent Way To Filter Laravel Models And Their Relationships

Eloquent Filter An Eloquent way to filter Eloquent Models and their relationships Introduction Lets say we want to return a list of users filtered by

A Laravel 8 and Livewire 2 demo showing how to search and filter by tags, showing article and video counts for each tag (Polymorphic relationship)
A Laravel 8 and Livewire 2 demo showing how to search and filter by tags, showing article and video counts for each tag (Polymorphic relationship)

Advanced search and filter with Laravel and Livewire A demo app using Laravel 8 and Livewire 2 showing how to implement a list of articles and tags, v

An Eloquent Way To Filter Laravel Models And Their Relationships

Eloquent Filter An Eloquent way to filter Eloquent Models and their relationships Introduction Lets say we want to return a list of users filtered by

Filter resources with request parameters

FilterWhere Filter resources with request parameters Author: Thomas Jakobi [email protected] License: GNU GPLv2 Features With this MODX Revolu

A generic filter for contao entities.

Contao filter bundle This bundle offers a generic filter module to use with arbitrary contao entities containing standard filter with initial filters

A Laravel package that provides configurable application query capturing & monitoring
A Laravel package that provides configurable application query capturing & monitoring

Laravel Query Watcher A Laravel package that provides configurable application query capturing & monitoring. Installation install the package via comp

A simple laravel package to handle multiple key based model route binding

Laravel Model UUID A simple package to handle the multiple key/column based route model binding for laravel package Installation Require the package u

Releases(1.0.0)
Owner
Touhidur Rahman
Husband, father, big time documentary tv series lover and software engineer . Passionate about PHP, Laravel, Ruby on Rails, Vue.js and C/C++ . Learning Rust .
Touhidur Rahman
A collection of common algorithms implemented in PHP. The collection is based on "Cracking the Coding Interview" by Gayle Laakmann McDowell

PHPAlgorithms A collection of common algorithms implemented in PHP. The collection is based on "Cracking the Coding Interview" by Gayle Laakmann McDow

Doğan Can Uçar 921 Dec 18, 2022
Stop duplicating your Eloquent query scopes and constraints in PHP. This package lets you re-use your query scopes and constraints by adding them as a subquery.

Laravel Eloquent Scope as Select Stop duplicating your Eloquent query scopes and constraints in PHP. This package lets you re-use your query scopes an

Protone Media 75 Dec 7, 2022
A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)

Laravel MongoDB This package adds functionalities to the Eloquent model and Query builder for MongoDB, using the original Laravel API. This library ex

Jens Segers 6.3k Jan 7, 2023
A DynamoDB based Eloquent model and Query builder for Laravel.

Laravel DynamoDB A DynamoDB based Eloquent model and Query builder for Laravel. You can find an example implementation in kitar/simplechat. Motivation

Satoshi Kita 146 Jan 2, 2023
A query database collection for use with Laravel Pipeline

A query database collection for use with Laravel Pipeline This package contains a collection of class that can be used with Laravel Pipeline. Let's se

Dương Gia Bảo 188 Dec 24, 2022
A laravel package to generate model hashid based on model id column.

Laravel Model Hashid A package to generate model hash id from the model auto increment id for laravel models Installation Require the package using co

Touhidur Rahman 13 Jan 20, 2022
🖖Repository Pattern in Laravel. The package allows to filter by request out-of-the-box, as well as to integrate customized criteria and any kind of filters.

Repository Repository Pattern in Laravel. The package allows to filter by request out-of-the-box, as well as to integrate customized criteria and any

Awes.io 160 Dec 26, 2022
Update multiple Laravel Model records, each with it's own set of values, sending a single query to your database!

Laravel Mass Update Update multiple Laravel Model records, each with its own set of values, sending a single query to your database! Installation You

Jorge González 88 Dec 31, 2022
Joomla Framework Filter Package

The Filter Package Installation via Composer Add "joomla/filter": "~2.0.*@dev" to the require block in your composer.json and then run composer instal

Joomla! Framework 10 Dec 16, 2022
Collection of the Laravel/Eloquent Model classes that allows you to get data directly from a Magento 2 database.

Laragento LAravel MAgento Micro services Magento 2 has legacy code based on abandoned Zend Framework 1 with really ugly ORM on top of outdated Zend_DB

Egor Shitikov 87 Nov 26, 2022