Laravel 5.2 search query

Here is the very last problem I have encountered. I am trying to implement a search in my application, and I know how to do it when it comes to finding your tables for keywords using where('firstname', 'LIKE', %$search%), etc. However, how I would like to narrow my search based on the criteria that the user sets. For a quick search for the keyword $, as well as $ city and $ pricePoint.

I'm just trying to figure out how to structure the request in php so that if the user sets the $ keyword and the city, he searches for it, and if the user only sets the $ keyword, there is no urban aspect of the request.

The project is based on Laravel 5.2 and in the mysql database. Any help is appreciated.

0
source share
1 answer

Suppose there are 3 criteria: the 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, do something more general by doing a list of criteria and iterating through them using a loop instead of adding other if conditions.

+3
source

Source: https://habr.com/ru/post/1659259/


All Articles