dimanche 1 juillet 2018

Return rows based on multiple field search

Lets say I have a table with fields:

name, email, designation, city

What I want is that a user can search records by entering single word or multiple words in a single search box. eg. ABC abc@gmail.com

Right now I am using something like this:

$keywords = $request->get('search');
$searchValues = preg_split('/\s+/', $keywords, -1, PREG_SPLIT_NO_EMPTY);

$users = DB::table('users')
                    ->select('name', 'email',  'designation', 'city')
                    ->where(function ($query) use($searchValues){

                        foreach ($searchValues as $value)
                        {
                            $query->orWhere('name', 'like', "%{$value}%")
                                  ->orWhere('email', 'like', "%{$value}%")
                                  ->orWhere('designation', 'like', "%{$value}%")
                                  ->orWhere('city', 'like', "%{$value}%");
                        }
            })->latest('users.created_at')->paginate($perPage);

This works but has a problem that it returns all users with name 'ABC' rather than returning only rows with name='ABC' and email='abc@gmail.com'

How can I achieve this ?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire