Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mediax's avatar

Relation between 3 tables?

I have 3 tables (also 3 models), User, Company and UserCompany, (images here: http://prntscr.com/dguedl), I have a page where I get all companies from a user this is table UserCompany, there I get company id, how can I create now relation (which type) to get company name?

0 likes
3 replies
mediax's avatar

@mstnorris I have a page if user is logged in then he become assigned companies listed, in the table UserCompany are companies assigned to user, user can has more companies.

I list here assigned companies id's, there are in UserCompany, but I want to use Model Company to get company name. How can I use it in blade?

I list assigned companies with help from following relation:

    public function userCompanies() {
        return $this->hasMany('App\Models\UserCompany');
    }

And this is blade file:

    @foreach($userCompanies as $userCompany)
            <li><a href="">{{ $userCompany->company_id }}</a></li>
        @endforeach
1 like
willvincent's avatar
Level 54

If it's a many to many relationship your relationships would look like this:

User model:

public function companies() {
  return $this->belongsToMany(App\Models\Company::class);
}

Company model:

public function users() {
  return $this->belongsToMany(App\Models\User::class);
}

Then you could say: $user = User::with('companies')->findOrFail(Auth::id()); to load the current user, with their associated companies, for example..

Might need to specify tables/keys on those relations if you didn't follow the expected conventions for table and key naming.

Docs on Many to Many relationships: https://laravel.com/docs/5.3/eloquent-relationships#many-to-many

Please or to participate in this conversation.