0

I apologize in advance if this question is too specific but I am having a hard time choosing the right eloquent relationship between these two models. I have two models, one named "Package" (for example a travel package) and another called "Country". A package can only have one country and a country can have multiple packages. This is my relationship:

class Package extends Model
{
    public function country()
    {
        return $this->belongsTo('App\Country');
    } 
}    

// Country
class Country extends Model
{
    public function packages()
    {
        return $this->hasMany('App\Country');
    } 
}    

Is this the right relationship? When I use the following relationship and I want to get a collection of packages with country information using the code below:

$packages = Package::with('country')->get();

I get NULL on the countries response. Am I doing anything wrong? Thank you for your assistance.

PS: This is my database structure:

Country:
    `id`
    `iso_code`
    `name`
    `phone_code`

Package:
    `id`
    `title`
    `description`
    `date_from`
    `date_to`
    `price`
    `country_id`
realnsleo
  • 709
  • 2
  • 12
  • 29
  • 1
    What does your database table structure for the two tables look like? – D Malan Mar 19 '19 at 07:25
  • @DelenaMalan I have edited my question and added the structure of the tables – realnsleo Mar 19 '19 at 07:30
  • 1
    In your Country Class you have to remove the method Country. In that Class you need to call the Package and because it's a 'has many' relation it's best practise to write it plural 'Packages' so you know it returns multiple packages. – EnzoTrompeneers Mar 19 '19 at 07:36

1 Answers1

4

Try this:

// Package
class Package extends Model
{
    public function country()
    {
        return $this->belongsTo('App\Country');
    } 
}    

// Country
class Country extends Model
{
    public function packages()
    {
        return $this->hasMany('App\Package', 'country_id', 'id');
    } 
}
Inzamam Idrees
  • 1,955
  • 14
  • 28