Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

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?

Last updated 2 years ago.
0

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.

Last updated 2 years ago.
0

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.

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.