Many users belong to one team which belongs to one project - relationship problems

Posted 1 month ago by danhorton


in the site I am building, there is a project which is the main component of the application. A project has one team, which in turn can have many users associated with it.

I have clearly forgotten how to set up relationships as I am having trouble with this.

A project has one team (although if I do it this way, laravel does a select top 1 query from the teams table, which holds multiple user records inside)

    public function team()
        return $this->hasOne('App\Team');

Then, a team has many users

    public function user()
        return $this->hasMany('App\User', 'id', 'user_id');

If I {{dd($bid->team)}} on a project with a team and users associated, it returns this:

Collection {#678 ▼
  #items: array:2 [▼
    0 => Team {#675 ▶}
    1 => Team {#676 ▶}

Which is 1 team object for every row in the teams database.

To access the users, I have to do $bid->team[0]->user->name etc rather than $bid->team->user->name as each user is attached to its own team object rather than 1 team object having many users related.

What am I doing wrong here?

Please sign in or create an account to participate in this conversation.

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up


Reply to

Use Markdown with GitHub-flavored code blocks.