My question is actually from the category of puzzles and "how it can be done more simple and still working". Academic knowledge most of all...
Anybody?
The query builder and Eloquent are not separate ways to query, they work together. You can use any of the query builder methods with Eloquent. It seems you have a decent handle on it.
You can use scope for that, that's probably all:
// Airport model
public function scopeSearchWithCitiesAndCountries($query, $keyword)
{
$query
->leftJoin('cities', 'airports.city_id', '=', 'cities.id')
->leftJoin('countries', 'cities.country_id', '=', 'countries.id');
if($keyword)
{
$query
->where(function($q) use ($keyword)
{
$q
->where('airports.name', 'like', $keyword.'%')
->orWhere('airports.iata_code', 'like', $keyword.'%')
->orWhere('airports.icao_code', 'like', $keyword.'%')
->orWhere('cities.name', 'like', $keyword.'%')
->orWhere('countries.name', 'like', $keyword.'%')
;
})
;
}
}
Then:
$city_name = 'Pari';
$airports = Airport::whereNotNull('icao_code')->searchWithCitiesAndCountries($city_name)->get();
That scope could be further refactored, you can extract some of it to separate methods etc.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community