A simple to use query builder for the jQuery QueryBuilder plugin for use with Laravel.

Overview

QueryBuilderParser

Status Label Status Value
Build Build Status
Insights SensioLabsInsight
Code Climate Code Climate
Test Coverage Coverage Status

QueryBuilderParser is designed mainly to be used inside Laravel projects, however it can be used outside Laravel projects by using Illuminate/Database.

A simple to use query builder for the jQuery QueryBuilder plugin.

Using QueryBuilderParser

Building a new query from QueryBuilder rules.

    use timgws\QueryBuilderParser;

    $table = DB::table('table_of_data_to_integrate');
    $qbp = new QueryBuilderParser(
        // provide here a list of allowable rows from the query builder.
        // NOTE: if a row is listed here, you will be able to create limits on that row from QBP.
        array( 'name', 'email' )
    );

    $query = $qbp->parse($input['querybuilder'], $table);

    $rows = $query->get();
    return Response::JSON($rows);

jQuery QueryBuilder

This query when posted will create the following SQL query:

SELECT * FROM table_of_data_to_integrate WHERE `name` LIKE '%tim%' AND `email` LIKE '%@gmail.com'

Getting results from MongoDB

    use timgws\QueryBuilderParser;

    $table = DB::collection('data');
    $qbp = new QueryBuilderParser(
        // provide here a list of allowable rows from the query builder.
        // NOTE: if a row is listed here, you will be able to create limits on that row from QBP.
        array( 'name', 'email' )
    );

    $query = $qbp->parse($input['querybuilder'], $table);

    $rows = $query->get();
    return Response::JSON($rows);

This query when posted will create the following MongoDB query:

    {
      "$and": [
        {
          "name": {
            "$regex": "tim"
          }
        },
        {
          "email": {
            "$regex": "@gmail\\.com$"
          }
        }
      ]
    }

Note that to use this you will need to install and configure jenssegers/mongodb.

Integration examples

Integrating with jQuery Datatables

Mixed with Datatables, jQuery QueryBuilder makes for some true awesome, allowing limitless options for filtering data, and seeing the results on the fly.

    use timgws\QueryBuilderParser;
    
    class AdminUserController {
        function displayUserDatatable() {
            /* builder is POST'd by the datatable */
            $queryBuilderJSON = Input::get('rules');
            
            $show_columns = array('id', 'username', 'email_address');
            
            $query = new QueryBuilderParser($show_columns);
            
            /** Illuminate/Database/Query/Builder $queryBuilder **/
            $queryBuilder = $query->parse(DB::table('users'));
            
            return Datatable::query($queryBuilder)
                ->showColumns($show_columns)
                ->orderColumns($show_columns)
                ->searchColumns($show_columns)
                ->make()
        }
    }

On the client side, a little bit of magic is required to make everything work.

    // the default rules, what will be used on page loads...
    var datatablesRequest = {};
    var _rules = defaultRules = {"condition":"AND","rules":[
        {"id":"active","field":"active","type":"integer","input":"radio","operator":"equal","value":"1"}
    ]};

    // a button/link that is used to update the rules.
    function updateFilters() {
        _rules = $('#querybuilder').queryBuilder('getRules');
        reloadDatatables();
    }

    function filterChange() {
        var _json = JSON.stringify( _rules );
        datatablesRequest = { rules: _json };
    }

    filterChange();

    function reloadDatatables() {
        /* Datatables first... */
        filterChange();

        $('.dataTable').each(function() {
            dt = $(this).dataTable();
            dt.fnDraw();
        })
    }

    jQuery(document).ready(function(){
        // dynamic table
        oTable = jQuery('.datatable').dataTable({
            "fnServerParams": function(aoData) {
                // add the extra parameters from the jQuery QueryBuilder to the Datatable endpoint...
                $.each(datatablesRequest , function(k,v){
                    aoData.push({"name": k, "value": v});
                })
            }
        })
    });

Using JoinSupportingQueryBuilderParser

JoinSupportingQueryBuilderParser is a version of QueryBuilderParser that supports building even more complex queries.

    $joinFields = array(
        'join1' => array(
            'from_table'      => 'master',
            'from_col'        => 'm_col',
            'to_table'        => 'subtable',
            'to_col'          => 's_col',
            'to_value_column' => 's_value',
        ),
        'join2' => array(
            'from_table'      => 'master2',
            'from_col'        => 'm2_col',
            'to_table'        => 'subtable2',
            'to_col'          => 's2_col',
            'to_value_column' => 's2_value',
            'not_exists'      => true,
        )
    );

    $table = DB::table('table_of_data_to_integrate');
    $jsqbp = new JoinSupportingQueryBuilderParser($fields, $this->getJoinFields());
    $test = $jsqbp->parse($json, $builder);

Which will build an SQL query similar to:

select * where exists (select 1 from `subtable` where subtable.s_col = master.m_col and `s_value` < ?)

For simple queries, QueryBuilderParser should be enough.

Exporting CSV files

Just as a footnote, there are right ways to export CSV files, and there are wrong ways.

For the right way, check out the question on StackOverflow, How can I output a UTF-8 CSV in PHP that Excel will read properly?

Reporting Issues

I use this code in a number of my projects, so if you do find an issue, please feel free to report it with GitHub's bug tracker for this project.

Alternatively, fork the project and make a pull request :)

Comments
  • Cast datetimes and add 'not between' operator

    Cast datetimes and add 'not between' operator

    I accidentally merged #21.

    This work was mainly done by @sgjackman @wpanec-uno. Thanks for the contribution peeps!

    Please note my comment about dates, this change still needs testing! https://github.com/timgws/QueryBuilderParser/pull/21#issuecomment-340354857

    opened by timgws 7
  • JoinSupportingQueryBuilderParser is not working with

    JoinSupportingQueryBuilderParser is not working with "is_null" operator

    Hi,

    I added the is_null operator on the QueryBuilder but it seems to be parsed like a value, the resulting SQL query looks like: ... field_name = "NULL" ...

    but it should be like this: ... field_name IS NULL ...

    I will try to make a test with this case in a few days.

    Thank you again!

    opened by milhouse1337 7
  • Date fields don't work with 'between' operator

    Date fields don't work with 'between' operator

    Dates were not being cast as dates, so if you have a query that was filtering between two dates it won't work.

    Simple fix would be to turn any field of date into a Carbon object. I did this by editing the getValueForQueryFromRule method like this (just before returning the value)

    	 if ( $rule->type == 'datetime' ) {
    		if ( is_array( $value ) ) {
    			$value = array_map( function ( $v ) {
    				return new Carbon( $v );
    			}, $value );
    		} else {
    			$value = new Carbon( $value );
    		}
    	}
    
    opened by sgjackman 5
  • Remove

    Remove "input" from required rule fields, because it's not guaranteed to exist

    input field will be omitted from rules json when a function is used to generate it:

    {
      id: 'test',
      type: 'string',
      input: function(rule, input_name) {
        return `<input class="form-control" type="text" name=${input_name} />`
      }
    }
    

    QueryBuilderParser will then do an overzealous check, and drop the rule all together from the query.

    It's worth considering that most rule fields are not guaranteed to exist: https://github.com/mistic100/jQuery-QueryBuilder/blob/2a237884b8a665ed9757a4ce08166b8d9e2b24d6/src/public.js#L257-L264

    Perhaps id and type do not need to be verified for existence either?

    opened by VanTanev 5
  • Can't install on 5.7

    Can't install on 5.7

    Can't composer require this for 5.7, get this error:

    timgws/query-builder-parser 1.5 requires illuminate/database 4.1 - 5.6

    Possible to push your 5.8 changes? Or at least just the composer file to allow 5.7.* in the meantime?

    opened by kejodion 4
  • Filtering though multiple joins

    Filtering though multiple joins

    Hi,

    dont know if you are still supporing this project, but i would like to have a question. I made an implementation of your filter in my laravel project. Working fine. Also could make the Join filtering work.

    So if i want to get all my contracts with a partner located in a specific country i can just go:

    protected $joins = [
            'country_id' =>  [
                'from_table'      => 'contract',
                'from_col'        => 'partner_id',
                'to_table'        => 'partner',
                'to_col'          => 'partner_id',
                'to_value_column' => 'country_id'
            ]
    ];
    

    and i can get all contracts where partner got a country_id of 22 for example.

    Now my question is how would you go about a fied that goes over multiple tables.

    contract->partner->partner_service->service_charge

    i need now all contracts with a charge of "50".

    Would this be possible or is it a new feature?

    opened by T0miii 4
  • Laravel 5.5 support

    Laravel 5.5 support

    timgws/query-builder-parser 1.3 requires illuminate/database 4.1 - 5.4 -> satisfiable by laravel/framework[v5.4.33], illuminate/database[4.1.x-dev, 4.2.x-dev, 5.0.x-dev, 5.1.x-dev, 5.2.x-dev, 5.3.x-dev, 5.4.x-dev, v4.1.0, v4.1.1, v4.1.10, v4.1.11, v4.1.12, v4.1.13, v4.1.14, v4.1.15, v4.1.16, v4.1.17, v4.1.18, v4.1.19, v4.1.2, v4.1.20, v4.1.21, v4.1.22, v4.1.23, v4.1.24, v4.1.25, v4.1.26, v4.1.27, v4.1.28, v4.1.29, v4.1.3, v4.1.30, v4.1.4, v4.1.5, v4.1.6, v4.1.7, v4.1.8, v4.1.9, v4.2.0-BETA1, v4.2.1, v4.2.12, v4.2.16, v4.2.17, v4.2.2, v4.2.3, v4.2.4, v4.2.5, v4.2.6, v4.2.7, v4.2.8, v4.2.9, v5.0.0, v5.0.22, v5.0.25, v5.0.26, v5.0.27, v5.0.28, v5.0.33, v5.0.4, v5.1.1, v5.1.13, v5.1.16, v5.1.2, v5.1.20, v5.1.22, v5.1.25, v5.1.28, v5.1.30, v5.1.31, v5.1.41, v5.1.6, v5.1.8, v5.2.0, v5.2.19, v5.2.21, v5.2.24, v5.2.25, v5.2.26, v5.2.27, v5.2.28, v5.2.31, v5.2.32, v5.2.37, v5.2.43, v5.2.45, v5.2.6, v5.2.7, v5.3.0, v5.3.16, v5.3.23, v5.3.4, v5.4.0, v5.4.13, v5.4.17, v5.4.19, v5.4.27, v5.4.36, v5.4.9].

    opened by eelco2k 3
  • JoinSupportingQueryBuilderParser always return AND even if OR is the condition

    JoinSupportingQueryBuilderParser always return AND even if OR is the condition

    Hi there,

    First of all this is a great stuff, thank you for this.

    I noticed a small bug, when I select OR in the QueryBuilder the parser always seperate them with AND instead of OR statements.

    Here is an example query output:

    select * from table where exists (...) and exists (...)

    Not sure but I think it comes from this: https://github.com/timgws/QueryBuilderParser/blob/master/src/QueryBuilderParser/JoinSupportingQueryBuilderParser.php#L117

    I will try to make a test for this case later.

    Thank you!

    opened by milhouse1337 3
  • Fix query condition to be from the correct level in hierarchy

    Fix query condition to be from the correct level in hierarchy

    As per https://github.com/timgws/QueryBuilderParser/issues/5 the query condition is currently being taken from the wrong level in the parse tree. This fixes that - but is definitely a breaking change for any dependent code, since it changes many and/or conditions.

    opened by simplesi 3
  • Laravel 9 compatibility

    Laravel 9 compatibility

    Hello,

    I try to install the library on Laravel 9 but I have the following errors:

    Problem 1
        - illuminate/database[v5.6.0, ..., 5.8.x-dev] require php ^7.1.3 -> your php version (8.1.0) does not satisfy that requirement.
        - illuminate/database[v6.0.0, ..., v6.19.1] require php ^7.2 -> your php version (8.1.0) does not satisfy that requirement.
        - illuminate/database[v7.0.0, ..., v7.28.4] require php ^7.2.5 -> your php version (8.1.0) does not satisfy that requirement.
        - illuminate/database[v8.0.0, ..., v8.11.2] require php ^7.3 -> your php version (8.1.0) does not satisfy that requirement.
        - Root composer.json requires timgws/query-builder-parser dev-master -> satisfiable by timgws/query-builder-parser[dev-master].
        - Conclusion: don't install laravel/framework v9.3.0 (conflict analysis result)
        - Conclusion: don't install laravel/framework v9.3.1 (conflict analysis result)
        - Conclusion: don't install laravel/framework v9.2.0 (conflict analysis result)
        - timgws/query-builder-parser dev-master requires illuminate/database ^8.0||^7.0||^6.0||4.1 - 6.0 -> satisfiable by illuminate/database[v4.1.0, ..., 4.2.x-dev, v5.0.0, ..., 5.8.x-dev, v6.0.0, ..., 6.x-dev, v7.0.0, ..., 7.x-dev, v8.0.0, ..., 8.x-dev].
        - Only one of these can be installed: illuminate/database[v4.1.0, ..., 4.2.x-dev, v5.0.0, ..., 5.8.x-dev, v6.0.0, ..., 6.x-dev, v7.0.0, ..., 7.x-dev, v8.0.0, ..., 8.x-dev, v9.0.0-beta.1, ..., 9.x-dev], laravel/framework[v9.2.0, v9.3.0, v9.3.1, 9.x-dev]. laravel/framework replaces illuminate/database and thus cannot coexist with it.
        - Root composer.json requires laravel/framework ^9.2 -> satisfiable by laravel/framework[v9.2.0, v9.3.0, v9.3.1, 9.x-dev].
    

    Can you update your library for Laravel 9?

    Thank you!

    opened by david-fanin 2
  • mongoDB aggregation

    mongoDB aggregation

    hello, I would like to know if it is possible to join (aggregate) for mongoDB? Because the library is very nice, but to use it on a day-to-day basis, I need to be able to do aggregation for mongoDB.

    Or if it is not possible to join (aggregate) for mongoDB with the library, if you have any alternative to be able to do it.

    opened by GlauberF 2
  • append  new group of conditions

    append new group of conditions

    hello , I am trying to append a new group of conditions in the background and in this group, I want to use OR and the relation between this group and the group that was submitted by the user will be AND so this is how it will work group1 which is submitted by a user group 2 which I want to add in the background the relation between group1 and group2 is AND and the conditions in group2 are OR how can I do that? how can I push my conditions in the condition that the customer has been sent?

    opened by starking8b 0
  • Better handling of not_equal operator

    Better handling of not_equal operator

    I came across a use-case where not_equal does not produce the result I expected because of the following MySQL behavior: https://stackoverflow.com/questions/16186674/mysql-syntax-not-evaluating-not-equal-to-in-presence-of-null

    Could you consider changing the way the not_equal operator is translated in MySQL? It should be (but I know this is a personal opinion) NOT column <=> value.

    Full disclosure: I'd like to avoid my users create a query column IS NULL OR column != value.

    Let me know what you think :) Or if it's unclear.

    opened by julienmru 1
  • Support date ranges being converted to SQL and MongoDB queries with jQuery-QueryBuilder

    Support date ranges being converted to SQL and MongoDB queries with jQuery-QueryBuilder

    I have a database-design where the date I want to query is of the datetime-type. But when I try to select all orders that equal to todays date for example, the parser will add 00:00:00 and I will not get any results.

    I usually solve this to use the mysql date function (select * from orders where order_date = date('2019-06-28')) - is there any way to do this with the QueryBuilderParser?

    I now manually loop through the rules and rebuild an equals to to between and manipulate fields, but I hope this can be done more easily?

    sql mongodb good first issue 
    opened by VoordeMensen 1
  • Custom bindings for fields

    Custom bindings for fields

    Hello, it would be helpful to be able to create bindings for fields similarly at what is done for JoinSupportingQueryBuilderParser. If I store some values within json columns I can't use the parser to filter on these fields easily. Something like that could be usefull :

    $bindingsFields = array(
            'myjsonfield1' => array(
                'from_table'      => 'table1',
                'from_col'        => 'json_col',
                'json_path'        => 'json_fields->myjsonfield1->myjsonfield1->value' // should be optional if field is not within a json column
            ),
    
    
    opened by curunoir 0
  • Documentation Suggestion

    Documentation Suggestion

    In Using QueryBuilderParser you use DB::table and DB::collection. May I suggest adding the namespace for these. That would make it easier to understand how to integrate with Illuminate, without Laravel.

    I'm making a pull request to the documentation of https://querybuilder.js.org/, to label your project for both Laravel and Illuminate. It's currently labelled just for Laravel.

    opened by galeaspablo 2
Releases(1.6.2)
Owner
Tim Groeneveld
WebRTC nerd at Vonex. Linux, Laravel, PHP, MySQL & nginx are my buzzwords. Check out @elasticquent and @OpenSkill for projects that I contribute to!
Tim Groeneveld
Textpattern-jquery-ui-theme - The jQuery UI theme used within the Textpattern CMS admin-side.

Textpattern jQuery UI theme The jQuery UI theme used within the Textpattern CMS admin-side. Supported web browsers Chrome, Edge, Firefox, Safari and O

Textpattern CMS 12 Jan 10, 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
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
Provides a Eloquent query builder for Laravel or Lumen

This package provides an advanced filter for Laravel or Lumen model based on incoming requets.

M.Fouladgar 484 Jan 4, 2023
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 WPDB wrapper and query builder library.

DB A WPDB wrapper and query builder library. Installation It's recommended that you install DB as a project dependency via Composer: composer require

StellarWP 35 Dec 15, 2022
Laravel style jquery validation plugin

Validator Laravel style jquery validation plugin Validator is a jQuery plugin that emulates the validation class found in the laravel framework. Usage

David Thingsaker 5 Aug 31, 2022
Server-side handler of DataTables Jquery Plugin for Laravel 4

Project is not being maintained actively. You will most likely find a better more actively maintained fork here https://github.com/yajra/laravel-datat

Bilal Gultekin 264 Jul 2, 2022
jQuery DataTables API for Laravel 4|5|6|7|8

jQuery DataTables API for Laravel 4|5|6|7|8 This package is created to handle server-side works of DataTables jQuery Plugin via AJAX option by using E

Arjay Angeles 4.5k Jan 9, 2023
Laravel router extension to easily use Laravel's paginator without the query string

?? THIS PACKAGE HAS BEEN ABANDONED ?? We don't use this package anymore in our own projects and cannot justify the time needed to maintain it anymore.

Spatie 307 Sep 23, 2022
🎨 Free custom elements for the WordPress plugin Oxygen Builder.

?? Custom Elements for Oxygen Builder Free custom elements for the WordPress plugin Oxygen Builder. If you find the elements useful, click on the star

Simon Vidman 62 Dec 29, 2022
Use Laravel's built-in ORM classes to query cloud resources with Steampipe.

Laravel Steampipe Use Laravel's built-in ORM classes to query cloud resources with Steampipe, an open source CLI to instantly query cloud APIs using S

Renoki Co. 13 Nov 8, 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
A demo of how to use filament/forms to build a user-facing Form Builder which stores fields in JSON.

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Dan Harrin 41 Dec 24, 2022
A Pocketmine 4.0 Plugin which makes your server query = Current players + 1 Total Slots

The Better-Query Plugin This Plugin implements Better Query System **(i.e. 0/1 as player count)** the server total slots increases by 1 after a player

RealBJsingh 3 May 14, 2022
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

NIYIBIZI HIRWA 1 Aug 23, 2022
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

Syrian Open Source 15 Nov 20, 2022
Laravel Form builder for version 5+!

Laravel 5 form builder Form builder for Laravel 5 inspired by Symfony's form builder. With help of Laravels FormBuilder class creates forms that can b

Kristijan Husak 1.7k Dec 31, 2022