Support the ongoing development of Laravel.io →
Input Database Eloquent
Last updated 2 years ago.
0

Well that is a good question, and I want to hear some ideas too. Right now I am doing it this way. The code is heavily modified to serve only this thread so there may be errors.

I am doing it by ajax, and the filters in the input are json-encoded

public function search()
{
$filters=json_decode(Input::get('filters'),true);

return Article::where(function($query) use ($filters){
  foreach ((array)$filters as $key=>$value){
    if ($value){
      $query->where($key, '=', $value);
    }
   }
 })->paginate(20);
}

Clarification:

The (array) in

(array)$filters 

is there for the case when there is no filter available

The

if ($value)

is there for the case when the filter is there but has no values

Last updated 2 years ago.
0

I'll try to explain what I did in my project. There is certainely a better solution but it can give you a starting point.

First, I get all input from the $_GET

$input = Input::all();

Nothing too hard here. Then I build a new QueryBuilder.

$articles = Article::where( function($subquery) use($input) { /* Here goes your filter logic */ } )->paginate(20);

Note that you have to use your $input to access it in the anonymous function.

Now, you have to fill up the anonymous function to set (Or not) your filters. The following code goes into the anonymous function. It replaces the comment

if( isset($input['filter1']) )
{
  $subquery->where('filter1', $input['filter1']);
}

if( isset($input['filter2']) )
{
  $subquery->where('filter2', $input['filter2']);
}

...

Note that you don't need to call ->get() on the subquery, Eloquent does it for you.

###Important point !

I didnt try this code, there is a possibility you get an error if there is no filter at all.

I hope it helps you ;)

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.