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..
$product->countries->name
since you havecountries()
defined in your model and notcountry()
– Halnex