Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel relationships - accessing related value in view

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.

like image 480
PDevH Avatar asked Nov 09 '22 02:11

PDevH


2 Answers

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 }}
like image 95
Alexey Mezenin Avatar answered Nov 28 '22 13:11

Alexey Mezenin


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');

like image 36
Sandyandi N. dela Cruz Avatar answered Nov 28 '22 13:11

Sandyandi N. dela Cruz