philperusse / nova-column-filter

A Laravel Nova column queryer filter
MIT License
39 stars 12 forks source link

Like operator? #2

Closed mattivie14 closed 5 years ago

mattivie14 commented 5 years ago

Is there any way to use this to do a "like" operator, I know the value would have to be wrapped in '%' values as well. It would be awesome if this was possible. I don't understand how the filters work quite well enough to figure out how to tweak this to work, although I did look around and try. :) If it's possible please let me know!!

philperusse commented 5 years ago

Hi @mattivie14 You can do whatever you want in your class that extends this Filters.

Here's an example


use \philperusse\Filters\ColumnFilter;

class MyCustomColumnFilter extends ColumnFilter
{

   /**
    * Apply the filter to the given query.
    *
    * @param  \Illuminate\Http\Request  $request
    * @param  \Illuminate\Database\Eloquent\Builder  $query
    * @param  mixed  $value
    * @return \Illuminate\Database\Eloquent\Builder
   */    
  public function apply( Request $request, $query, $value )
  {
     $args = collect($value)->values()->filter(); //Remove any empty keys.
     if($args->isEmpty())
          return $query;

      if($args[1] == 'LIKE')  // The operator 
         $args[2] = '%' . $args[2]. '%'; //Add the surounding % if needed;

       return $query->where(...$args);
  }

public function options( Request $request ) : array
    {
        return array_merge(parent::options($request), [
            'columns' => [
                'name'      => 'Name',
                'age'       => 'Age',
            ],
            'operators' => [
                'LIKE' => 'LIKE',
             ]
        ]);
    }
mattivie14 commented 5 years ago

Thanks! The fact that $args[1] is the operator is what I was missing!