0
votes

I am very new to Laravel and I am experimenting at the moment. So I decided to try and make a relationship of a hypothetical Online product for sale which has a 'country_from' and 'country_to' field in the database. So long story short I made the relationship and whenever I make the product via the forms the data reflects in the database properly. However, when I try and display the data back (the name of the country) I get an error "Trying to get property 'name' of non-object".

Product Model

protected $fillable = [

    'country_from',
    'country_to',
    'title',
    'body',
    'price',
    'availability'
];

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

Country Model

protected $fillable = ['name'];

public static $rules = array('name'=>'required|min:3');

public function products(){
    return $this->hasMany('App\Product');

products table: id, user_id, category_id, country_id, country_forum, country_to, photo_id, title, body, price, availability, created_at, updated_at

countries table: id, name, created_at, updated_at

In my blade $product->country_from displays the proper value of the set id.

However, when I try to: $product->country->name I get:

ErrorException (E_ERROR) Trying to get property 'name' of non-object

Does anyone have any idea what I am doing wrong? I am totally new to Laravel and PHP and my bet is I am doing something wrong with the relationship, but I have no idea what..

2
Have you tried calling $product->countries->name since you have countries() defined in your model and not country()Halnex

2 Answers

1
votes

You are trying to get the name from an object called 'country'. However, you have defined the relationship as countries.

Suggest you change the name of the relationship on the Product model to be singular, as it is a belongs to relationship:

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

Then, when you call :

{{$product->country->name}}

If there is a country attached by the id, you will not have an exception due to a non-object.

However, there is another problem and this will still fail in its current state. You have defined your foreign key as country_to and country_from. Laravel, by default in the country() relationship is going to look for a field called country_id to match to. You will need to add the foreign key into the relationship directly for each type of relationship you want (a countryTo() and a countryFrom()) in order for it to work.

0
votes

You need to call the relationship function that is defined in Product model. The following should work:

{{$product->countries->name}}

You're calling ->country on product model which is never defined, hence you get the error.


NOTE I would recommend you change the relationship function from plural to singular like:

countries() to country() because a product can only belong to a single country.


Hope it helps!