1

I am using eloquent query to filter data. My query is like this and it is working perfectly for now.

$users = User::where('username','LIKE','%'.request('username').'%')
            ->where('first_name','LIKE','%'.request('first_name').'%')
            ->where('last_name','LIKE','%'.request('last_name').'%')
            ->where('gender','LIKE','%'.request('gender').'%')
            ->where('password','LIKE','%'.request('password').'%')
            ->SimplePaginate(15);

My request data was like this.

enter image description here

However I need to update this query for dynamic fields. There can be different fields. What I did was to send the request in an associative array. So, my request data turned into like this,

enter image description here

What I intend to do is to put all request data in a search array. Then use a loop to run like the above query. How can I do that?

P.S. I checked in the forum and found some similar questions. Some of them are outdated. Others didn't solve my problem.

2
  • You have your data and what are you trying to achieve again? Update or use data for another search query Commented Feb 5, 2019 at 6:07
  • I want to use new query using 'search' associative array to get the same result. If I use 'search' array, then I can put any number of field in the array. Commented Feb 5, 2019 at 6:11

3 Answers 3

4

If I understand you right you can do like this:

$search = request('search', []);
$users = User::query();

foreach($search as $field=>$value)
{
    $users = $users->where($field,'LIKE','%'.$value.'%');        
}

$users = $users->SimplePaginate(15);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. It works. P.S. what is the purpose of this '$users = User::query();' line?
@NabilFarhan You are welcome. it's start of your query because you don't have any condition after User:: all is formed in loop.
0

You can try this.

$search = $request->get('search');

User::where(function ($q) use ($search){    
          foreach ($search as $key=>$value) {
            if($value != null ){   
                $q->where($key, 'like', "%{$value}%");  
            }
          }
 })->get();

Comments

0

The where() clause can also accept an array. With that in mind, you could map over your search parameters and convert it to the format you want and then feed it into the query.

For example:

$search = [
    'first_name' => 'John',
    'last_name'  => 'Smith'
];

$filters = collect($search)->map(function($value, $key) {
    return  [$key, 'LIKE', "%{$value}%"];
})->values()->toArray();

return User::where($filters)->SimplePaginate(15);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.