How to load relationships on multiple levels?

Asked

Viewed 47 times

2

Hello, I am trying to perform searches in 3 related tables as follows Contracts belongsTo -> hasMany -> company_addresses. I would like to display company_addresses data in the Contracts view.

contracts
    id – integer
    company_id - integer
    title – string 

companies
    id - integer
    name – string

company_addresses
    id - integer
    company_id - integer
    address – string
    complement – string
    contact– string

Model Contracts

public function company()
{
    return $this->belongsTo(Company::class, 'company_id', 'id');
}

Model Companies

public function contracts ()
{
    return $this->hasMany(Contract::class);
} 
public function addresses()
{
    return $this->hasMany(CompanyAddress::class);
}

Model company_addresses

public function company()
{
    return $this->belongsTo(Company::class);
}

Code of the Contract Controller

 public function index()
 {
     $contract= Contract::with('companies.company_addresses')->get();
     return view(‘contract.view')->with(compact('contract'));
 }

So what am I doing wrong and how can I fix it? Any help is very valid.

Thank you from the start.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.