Wednesday, March 15, 2017

Laravel way to get model using method on related model

I have setup relations for Mall and City model in this way:

Mall model:

public function city() {
    return $this->belongsTo('App\City');
}

City model:

public function malls() {
    return $this->hasMany( 'App\Mall' );
}

I have a method in City class with returns all cities in nearby radius:

public function getNearby($lat, $long, $r) {
   // return array of id of cities in $r radius
}

When I want to get all malls in nearby cities, I do something like this:

function getMallsInNearby() {
    $city_ids = City::getNearby($lat, $long, $r');
    $all_malls = Mall::all();
    foreach ( $all_malls as $mall ) {
        $malls[] = (in_array($mall->city->id , $city_ids) ? $mall : null);
    }
    return array_filter($malls);
}

I tried to use whereHas() method on malls and city without any success. What is the best way to achieve this in Laravel with Eloquent relations?



via Hadu

Advertisement