max234435 max234435 - 1 month ago 15
MySQL Question

laravel 5.2 search query

Here is the most recent problem I have ran into. I'm trying to implement search into my application and I know how to do it when it comes to searching your tables for keywords with

where('firstname', 'LIKE', %$search%)
and such. However, how would I go about narrowing down a search based on what criteria the user specifies. For exlample search for $keyword but also a $city and $pricePoint.

I'm just trying to figure out how to structure the query in php so that if user specifies the $keyword and the city it searches for that, and if user only specifies the $keyword, the city aspect of the query is not present.

Project is build on Laravel 5.2 and mysql database. Any help is appreciated.

Answer

Suppose there are 3 criteria: $keyword, $city and $pricePoint. You can do:

$query = DB::table('users');
if (!empty($keyword)) {
    $query = $query->where('keyword', 'LIKE', '%'.$keyword.'%');
}
if (!empty($city)) {
    $query = $query->where('city', 'LIKE', '%'.$city.'%');
}
if (!empty($pricePoint)) {
    $query = $query->where('pricePoint', 'LIKE', '%'.$pricePoint.'%');
}
$results = $query->get();

Then you can of course make something more generic by doing a list of criteria and iterating through them with a loop instead of adding another if conditions.