Laravel Links - Access to Related Costs

I cannot find a solution to the seemingly simple problem of passing related data to a view. I have a "Company" model that belongs to the "Regions". I created relationships belongsToin my company 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 relation hasManyin 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 showController passes the variable for the session row successfully to the view, but at the moment when I want to access the associated data of the table with the following ... (table "region" with column area)

<p>Region: {{ $company->region->region }}</p> -->

... I get an error

"Trying to get a non-object property: (View: ..."

\, , composer.json. : clear mvc .

, . , , , ?

.

+4
3

, Laravel Model? Company, $primaryKey. Region companies? belongsTo. : $this->belongsTo('App\Models\Region', 'unusual_region_id');

+1

, , , . , , :

{{ empty($company->region) ? 'No region' : $company->region->region }}
+2

Have you tried:

dd($company->region)

and see what data it returns.

-1
source

Source: https://habr.com/ru/post/1667739/


All Articles