ALCHI
ALCHI

Reputation: 75

Laravel search multiple fields

I currently have a search function on my website, I need it to search 3 fields - appid, mobilenumber, email .

Right now once the user enters the data in the search box it searches all 3 but its not working.

Data is collected using GET.

Here is my query

http://www.example.com?id=1&searchall=07853637362

$mobile = INPUT::get('searchall');
$email = INPUT::get('searchall');
$appid = INPUT::get('searchall');

$data = DB::table('leads')
->when($mobile, function($query) use ($mobile){
    return $query->where('MobilePhone', $mobile);
})
->when($email, function($query) use ($email){
    return $query->where('Email', $email);
})
->when($appid, function($query) use ($appid){
    return $query->where('AppID', $appid);
})
->get();

So I need it to search each field until it finds the correct field value.

Upvotes: 0

Views: 294

Answers (3)

MatHatrik
MatHatrik

Reputation: 764

$mobile = INPUT::get('searchall');
$email = INPUT::get('searchall');
$appid = INPUT::get('searchall');

$data = DB::table('leads')
->when($mobile, function($query) use ($mobile){
                return $query->orWhere('MobilePhone', $mobile);
            })

            ->when($email, function($query) use ($email){
                return $query->orWhere('Email', $email);
            })

            ->when($appid, function($query) use ($appid){
                return $query->orWhere('AppID', $appid);
            })->get();

Upvotes: 4

jakub wrona
jakub wrona

Reputation: 2254

I don't understand why you need the same value from the user using 3 variables, so the following is the simplified version:

$searched = Input::get('searchall');

$matched = DB::table('leads')
->where('MobilePhone', $searched)
->orWhere('Email', $searched)
->orWhere('AppID', $searched)
->get();

Upvotes: 0

EddyTheDove
EddyTheDove

Reputation: 13259

To search data try with like

->when($mobile, function($query) use ($mobile){
     return $query->where('MobilePhone', 'like', '%'. $mobile . '%');
})

to actually search each field, use orWhere

$keywords = Input::get('searchall');
$data = DB::table('leads')
->where('mobilephone', '=', $keywords)
->orWhere('email', '=', $keywords)
->orWhere('AppID', '=', $keywords)
->get();

Upvotes: 0

Related Questions