I can't find a solution to a seemingly simple problem with passing related data to a view. I have a model 'Companies' that belongs to 'Regions'.
I've created the belongsTo
relationship in my Companies model
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
protected $table = 'companies';
protected $primaryKey = 'Comp_id';
protected $fillable = ['industrylink_id', 'region_id','companyname','contactno','regno','vatno','salaryroll','numemployees'];
public function employees(){
return $this->hasMany('App\Models\Employee');
}
public function region(){
return $this->belongsTo('App\Models\Region');
Also the hasMany
relation in the Region model:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Region extends Model
{
protected $table = 'regions';
public function companies(){
return $this->hasMany('App\Models\Company');
}
}
My show
Controller passes the variable for the session row successfully to the view, but the moment I want to access the related table data with the following... (table 'region' with column 'region')
<p>Region: {{ $company->region->region }}</p> -->
...I get the error
"Trying to get property of non-object: (View:..."
I've changed my models location to app\Models and I've made all the necessary namespace changes in the models & controllers, as well as the autoload in composer.json. I did a composer dump & config:clear and all of the other mvc references work.
I did not create migrations for the related tables since the tables exist and have standard reference data in it. I assume the relation created in the model is sufficient?
I'd appreciate some assistance.
Usually, you get this error when variable or relationship is empty, so make sure company is not empty and it has a region. If you're sure company is not empty, just check the relationship:
{{ empty($company->region) ? 'No region' : $company->region->region }}
Have you ensured that the existing table foreign keys are declared in your Laravel Model relationship methods? I see in your Company
model that you declared a $primaryKey
. What's the foreign key that references a Region
in your companies
table? Declare it in the 2nd parameter of the belongsTo
method. Example: $this->belongsTo('App\Models\Region', 'unusual_region_id');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With