Skip to content
This repository has been archived by the owner on Jun 12, 2024. It is now read-only.

DataFilter

Felice Ostuni edited this page Nov 11, 2015 · 9 revisions

DataFilter extends DataForm, each field you add and each value you fill in that form is used to build a where clause (by default using 'like' operator).
It should be used in conjunction with a DataSet or DataGrid to filter results.
It also support query scopes (see eloquent documentation), closures, and a cool DeepHasScope trait see samples:

   $filter = \DataFilter::source(new Article);

   //simple like 
   $filter->add('title','Title', 'text');

   //simple where with exact match
   $filter->add('id', 'ID', 'text')->clause('where')->operator('=');

   //custom query scope, you can define the query logic in your model
   $filter->add('search','Search text', 'text')
          ->scope('myscope');
      
   //cool deep "whereHas" (you must use DeepHasScope trait bundled on your model)
   //this can build a where on a very deep relation.field
   $filter->add('search','Search text', 'text')
          ->scope('hasRel','relation.relation.field');
   
   //closure query scope, you can define on the fly the where
   $filter->add('search','Search text', 'text')
          ->scope( function ($query, $value) {
         return $query->whereIn('field', ["1","3",$value]);
   });

   $filter->submit('search');
   $filter->reset('reset');
   
   $grid = \DataGrid::source($filter);
   $grid->add('nome','Title', true);
   $grid->add('{{ substr($body,0,20) }}...','Body');
   $grid->paginate(10);

   view('articles', compact('filter', 'grid'))
   # articles.blade
   {!! $filter !!}
   {!! $grid !!}

Since DataFilter use GET method, it's trivial to make filter-links:

/datafilter/uri?title=Article+10&search=1    search for "Article 10" in title
/datafilter/uri?category_id=1&search=1  search for articles related to Cat. 1

DataFilter can work with multiple fields or, if you prefer, you can add a generic single field to do a free search. This is how to: http://www.rapyd.com/rapyd-demo/customfilter

Note that, parameter's name is generally related to "datafilter fields" and not directly to the Entity.
DataFilter works making only "where", "whereHas" and using PDO parameter binding (so It's safe from SQL injection), however you must pay attention if you customize queries using scopes (you should use parameter binding too).

Clone this wiki locally