CodingLaravel

Solved. Laravel Error ‘Attempt to read property “nationality” on int’

I was getting an error in Laravel when trying to access a value from a related table, after defining relationships in the relevant models.

Attempt to read property "nationality" on int

I had defined the relationship in my model as follows:

public function nationality(){
return $this->belongsTo(Country::class, 'nationality', 'countryid');
}

After trying many things to fix the error, without success, and then having a nearly-identical relationship working, I changed the name of the method to ‘nation’ and it worked.

public function nation(){
return $this->belongsTo(Country::class, 'nationality', 'countryid');
}

In other words, your method name should be different from the field names.