Nabil Farhan
Nabil Farhan

Reputation: 1536

Laravel eloquent using loop

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.

Upvotes: 1

Views: 8540

Answers (3)

Mozammil
Mozammil

Reputation: 8750

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

Upvotes: 0

Jigar
Jigar

Reputation: 3261

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();

Upvotes: 0

yrv16
yrv16

Reputation: 2275

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

Upvotes: 4

Related Questions