PHPackages                             zazmaster/query-builder-parser-eloquent - 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. zazmaster/query-builder-parser-eloquent

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

zazmaster/query-builder-parser-eloquent
=======================================

Build complex Eloquent &amp; QueryBuilder queries automatically when using jQuery-QueryBuilder

0.2(6y ago)071MITPHPCI failing

Since Mar 3Pushed 6y ago1 watchersCompare

[ Source](https://github.com/ZAZmaster/QueryBuilderParserEloquent)[ Packagist](https://packagist.org/packages/zazmaster/query-builder-parser-eloquent)[ Docs](http://github.com/ZAZmaster/QueryBuilderParserEloquent)[ RSS](/packages/zazmaster-query-builder-parser-eloquent/feed)WikiDiscussions master Synced today

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

QueryBuilderParser
==================

[](#querybuilderparser)

Eloquent version of  with issue [timgws/QueryBuilderParser#18](https://github.com/timgws/QueryBuilderParser/issues/18)

Status LabelStatus ValueBuild[![Build Status](https://camo.githubusercontent.com/713accb6ba55b991eca24f3c01bce1a36b0a4db94e20792c6e0ea4fd3362c9eb/68747470733a2f2f7472617669732d63692e6f72672f74696d6777732f51756572794275696c6465725061727365722e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/timgws/QueryBuilderParser)Insights[![SensioLabsInsight](https://camo.githubusercontent.com/7fee8a55c607244edac08544d09d5c84b647748fe0dac64e8205f3ee32055977/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f37303430336530312d616433392d343131372d626465662d6430633039633338323535352f6d696e692e706e673f6272616e63683d6d6173746572)](https://insight.sensiolabs.com/projects/70403e01-ad39-4117-bdef-d0c09c382555)Code Climate[![Code Climate](https://camo.githubusercontent.com/7001fab06babf3068dad8271d0cb2671323c932b8119e59b35fe7afd6e000397/68747470733a2f2f636f6465636c696d6174652e636f6d2f6769746875622f74696d6777732f51756572794275696c6465725061727365722f6261646765732f6770612e737667)](https://codeclimate.com/github/timgws/QueryBuilderParser)Test Coverage[![Coverage Status](https://camo.githubusercontent.com/93478582f8c7c0cb363bb90b36810e4a8d5b30eed08f90d2a70bcca40a3d1ea4/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f74696d6777732f51756572794275696c6465725061727365722f62616467652e7376673f6272616e63683d6d6173746572)](https://coveralls.io/github/timgws/QueryBuilderParser?branch=master)**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](http://querybuilder.js.org/demo.html#plugins).

Using QueryBuilderParser
========================

[](#using-querybuilderparser)

Building a new query from QueryBuilder rules.
---------------------------------------------

[](#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](/querybuilder.png?raw=true "jQuery QueryBuilder")](/querybuilder.png?raw=true)

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

[](#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
====================

[](#integration-examples)

Integrating with jQuery Datatables
----------------------------------

[](#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
--------------------------------------

[](#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 = $parser->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`
