How to search from “name” column of multiple tables with a keyword in Laravel Eloquent

public function getHotelsByDestination($name){
$objs = Hotel::whereHas(‘country’, function($query) use($name) {
$query->where(‘countries.name’, ‘LIKE’, ‘%’.$name.’%’);
})
->orWhereHas(‘city’, function($query) use($name) {
$query->where(‘cities.name’, ‘LIKE’, ‘%’.$name.’%’);
})
->orWhereHas(‘township’, function($query) use($name) {
$query->where(‘townships.name’, ‘LIKE’, ‘%’.$name.’%’);
})
->orWhere(‘name’,’LIKE’,’%’.$name.’%’)
->get();

return $objs;
}

/*
Explanation::
– There are four tables: hotels, countries, cities and townships which are related.
– User enters a search keyword
which can be a hotel_name, country_name, city_name or township_name.
– Search whether that keyword is in “name” column of countries,cities,townships,and hotels.
– Display “HOTELS” that match keyword as their name or country_name or city_name or township_name.
*/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s