Sunday, 18 April 2021

Laravel running eloquent using Loop

 

https://stackoverflow.com/questions/54528074/laravel-eloquent-using-loo

$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.



Solution :


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

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

$users = $users->SimplePaginate(15);

No comments:

Post a Comment