0

I have 5 models with one pivot table Country Province City Area Tour tour_location. How to achieve below functionality?

$country->tours

$province->tours

$city->tours

$area->tours

Country.php HasMany Provinces

public function provinces()
{
    return $this->hasMany('App\Province', 'country_id', 'id');
}

Province.php HasMany Cities

public function cities()
{
    return $this->hasMany('App\City', 'province_id', 'id');
}

City.php HasMany Areas

public function areas()
{
    return $this->hasMany('App\Area', 'city_id', 'id');
}

Area.php BelongsToMany Tours

public function tours()
{
    return $this->belongsToMany('App\Tour', 'tour_locations');
}
Kenny Horna
  • 13,485
  • 4
  • 44
  • 71
Fay
  • 191
  • 1
  • 4
  • 15
  • You can ckeck this link https://stackoverflow.com/questions/15439853/get-local-href-value-from-anchor-a-tag – Manisha Mar 28 '19 at 12:51

1 Answers1

2

The direct way is do it with joins, another way is to make a custom relationship extending the hasManyThrough(). The third option -imo- is to use the Eloquent-has-many-deep package.

Using this package, you could do this:

class Country extends Model
{
    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;

    public function tours()
    {
        return $this
          ->hasManyDeep('App\Tour', ['App\Province', 'App\City', 'App\Area', 'area_tour']);
    }
}

Then in your controller:

// ...
$country = Country::find(1);
$tours = $country->tours;

Disclaimer: I'm not involved in this package in any way. I'm just suggesting it because is the simplest way to achieve your desired behavior.

Kenny Horna
  • 13,485
  • 4
  • 44
  • 71