The query filter bundle allows you to filter data from QueryBuilder and the Database.

Overview

Query Filter Bundle

Scrutinizer Code Quality GitHub Workflow Status Code Intelligence Status

What does it do? :)

The query filter bundle allows you to filter data from QueryBuilder and the Database. you can filter multiple columns at the same time and also you can filter relation fields with two-level deep and without any join in your query builder.

Installation

composer require bugloos/query-filter-bundle

Compatibility

  • PHP v7.4 or above
  • Symfony v4.4 or above

Usage

Suppose our database has the following tables with the following relations

Service running preview

Now we want to filter Book entity

We want filter Book entity by title column, so we can send filter data by Querystring or with array in inline code like this:

/*
 * Filter books by title column
*/
//Get api/book/index?filter[title]=text_for_search
OR
$filters = [
    'title' => 'text_for_search',
];
/*
 * Filter books by title column
*/
//Get api/book/index?filter[title]=text_for_search
OR
$filters = [
    'title' => 'text_for_search',
];

You just need to add QueryFilter class in controller:

use Bugloos\QueryFilterBundle\Service\QueryFilter;

The following code is in Book controller.

As you see, At first you should call for() method and pass QueryBuilder as parameter to this method

Then call parameters() method and pass filters request items

At the end you should call filter() method to run it

The return of filter method is Query Builder, so you can add anything else to Query Builder after filtering.
public function index(
    Request $request,
    BookRepository $bookRepository,
    QueryFilter $queryFilter
): Response {
    $queryBuilder = $bookRepository->createQueryBuilder('b');
    
    $queryBuilder = $queryFilter->for($queryBuilder)
        ->parameters($request->get('filters'))
        ->filter()
    ;
    
    return $queryBuilder->getQuery()->getResult();
}

If you want to filter the ManyToOne relation field or one level deep relation, you should add mapper.

To add a mapper, you call addMapper() method to add single mapper or call mappers() method to add multiple mappers with array

First parameter of addMapper() method is parameter name and second parameter is relation name and its field name, which separate by " . " sign

$mappers = [
    'country' => 'country.name',
];

For example we want to filter Book entity by its Country name. Book has ManyToOne relation with Country entity

/*
 * Filter books by country column
*/
//Get api/book/index?filter[country]=text_for_search
OR
$filters = [
    'country' => 'text_for_search',
];
/*
 * Filter books by country column
*/
//Get api/book/index?filter[country]=text_for_search
OR
$filters = [
    'country' => 'text_for_search',
];

The following code is in Book controller.

public function index(
    Request $request,
    BookRepository $bookRepository,
    QueryFilter $queryFilter
): Response {
    $queryBuilder = $bookRepository->createQueryBuilder('b');
    
    $queryBuilder = $queryFilter->for($queryBuilder)
        ->parameters($request->get('filters'))
        ->addMapper('country', 'country.name')
        ->filter()
    ;
    
    return $queryBuilder->getQuery()->getResult();
}

NOTE: There is no need to add your relationship join in Query builder because if join is not added, I will add it automatically. ;)

$queryBuilder = $bookRepository->createQueryBuilder('b');
OR
$queryBuilder = $bookRepository->createQueryBuilder('b')
    ->addSelect('country')   
    ->leftJoin('b.country', 'country')      
;

If you want to filter the ManyToMany relation field or two level deep relation, you should again add mapper

$mapper = [
    'age' => 'bookUsers.user.age',
];

For example we want to filter Book entity by its Writers age. Book has ManyToMany relation with User entity

/*
 * Filter books by Writers age column
*/
//Get api/book/index?filter[age]=31
OR
$filters = [
    'age' => 31,
];
/*
 * Filter books by Writers age column
*/
//Get api/book/index?filter[age]=31
OR
$filters = [
    'age' => 31,
];

The following code is in Book controller.

public function index(
    Request $request,
    BookRepository $bookRepository,
    QueryFilter $queryFilter
): Response {
    $queryBuilder = $bookRepository->createQueryBuilder('b');
    
    $queryBuilder = $queryFilter->for($queryBuilder)
        ->parameters($request->get('filters'))
        ->addMapper('age', 'bookUsers.user.age')
        ->sort()
    ;
    
    return $queryBuilder->getQuery()->getResult();
}

NOTE: You should know that you can filter data with multiple columns too, you just need to send multiple filter data with a Query string like this:

/*
 * Filter books by title and age
*/
//Get api/book/index?filter[title]=text&filter[age]=31
OR
$filters = [
    'title' => 'text',
    'age' => 31,
];

Suggestion

You can change two parameters with the config file, just make a yaml file in config/packages/ directory then you can change default cache time for queries and default relation separator as follows:

query_filter:
  default_cache_time: 3600
  separator: '.'

NOTE: You can set the cache time for each query separately and if you don't set any cache time, it uses default cache time in your config file

$queryBuilder = $queryFilter->for($queryBuilder)
    ->parameters($request->get('filters'))
    ->cacheTime(120)
    ->sort()
;

Contributing v beer

If you find an issue, or have a better way to do something, feel free to open an issue or a pull request.

You might also like...
Laravel Query Helper was developed for laravel 7.2+ to help you optimize sql queries
Laravel Query Helper was developed for laravel 7.2+ to help you optimize sql queries

Laravel Query Helper Laravel Query Helper was developed for laravel 7.2+ to help you optimize sql queries, this package will contain all advanced SQL

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

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

Laravel package to normalize your data before saving into the database.

This package helps you normalize your data in order to save them into the database. The Goal is to having separate classes that handle the data normalization, and thus can be tested independently.

If you are beginner in WordPress plugin development or if you want to develop your own store product plugin you use this plugin
If you are beginner in WordPress plugin development or if you want to develop your own store product plugin you use this plugin

hirwa-products-plugin If you are beginner in WordPress plugin development or if you want to develop your own store product plugin you use this plugin

Vandar Cashier is a Laravel package that allows you to seamlessly implement IPG and Direct Debit on your application

Vandar Cashier is a Laravel package that provides you with a seamless integration with Vandar services. Take a look at Vandar Documentation for more i

A Laravel package that allows you to validate your config values and environment.
A Laravel package that allows you to validate your config values and environment.

Table of Contents Overview Installation Requirements Install the Package Publishing the Default Rulesets Usage Creating a Validation Ruleset Using the

This Laravel Nova package allows you to manage media and media fields
This Laravel Nova package allows you to manage media and media fields

Nova Media Hub This Laravel Nova package allows you to manage media and media fields. Requirements php: =8.0 laravel/nova: ^4.0 Features Media Hub UI

Comments
  • I want to have global search

    I want to have global search

    I need to have a global search to search in all fields or some specified fields with just a single search, for example:

    /api/books/index?q=search%f2this should return all records that may have this search item in their fields

    | ID | Column A | Column B | Column C | Column D | Column E | |----|------------|-------------|-----------|----------|----------| | 1 | Search ABC | A | B | C | D | | 2 | See this | Next record | Just fake | Lorem | Ipsum | | 3 | Col A | Col B | Col C | Col D | Col E |

    For example, this search should return records with ID 1 and 2 because search terms splited by space can see in these records

    opened by mortezakarimi 0
Releases(v1.0.11)
Owner
Bugloos
A web development agency specialized in online software. With more than 15 years of experience in creating customized web solutions
Bugloos
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
Serialization for Eloquent's QueryBuilder

Serialization for Eloquent's QueryBuilder Installation composer require anourvalar/eloquent-serialize Usage Serialize $package = \EloquentSerialize::s

Nick 64 Dec 14, 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
Save Model is a Laravel package that allows you to save data in the database in a new way.

Save Model is a Laravel package that allows you to save data in the database in a new way. No need to worry about $guarded and $fillable properties in the model anymore. Just relax an use Save Model package.

Laratips 27 Mar 2, 2022
A package to filter laravel model based on query params or retrieved model collection

Laravel Filterable A package to filter laravel model based on query params or retrived model collection. Installation Require/Install the package usin

Touhidur Rahman 17 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
A Laravel wrapper for spatie/dns. Allows to query and validate DNS records.

A Laravel wrapper for spatie/dns. Allows to query and validate DNS records.

Astrotomic 22 Nov 17, 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
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
Keyword Generator Tool helps you discover keyword opportunities related to your query input.

This plugin simply helps you discover keyword opportunities related to your query input. Installation Download the zip file of the repository or clone

WP Refers 1 May 3, 2022