Pivot table as main focus

Posted 1 year ago by ThePoet444

ok, using laravel 5.4, I have 3 models. Team, User, and positions. User can belong to many teams, teams can have many users. Both can have many positions.

slots  //max number of users on said team


title  //nullable field 

I was originally calling Positions and then eager loading both team and user. Then after thought, I realized positions was just a pivot table with a fancy name. So then I adjusted my relationship code to this:

public function user()
        return $this->belongsToMany(User::class, 'positions')
            ->withPivot('slot', 'title')

So now I have to display a team with all it's users in their correct spot and display empty spaces.

team controller:
public function show(team $team)
        $positions = Position::where('team_id', $team->id)->orderBy('slot', 'asc')->get()->keyBy('slot');

        return view('team.show', [
            'team' => $team,
            'positions' => $positions

 @for($i=1; $i<=$team->slots; $i++)
    @if((!empty($positions[$i])) && ($positions[$i]->slot == $i))
            <td>{{$positions[$i]->title ?: ''}}</td>

I can't help but think that I'm either over complicating this, or there's a better way. If what I'm doing is fine, why do I keep looking over it thinking that it's wrong? It works, and displays everything how I want, but still. I wonder what improvements I could make.

I tried making a Positions model that extended Pivot instead of model, but I realized I couldn't call it like a regular model (I can in laravel 5.5 though). So for now positions is just a regular model that belongsto bot User and Team.

PS. Thank goodness for StackEdit so I know my code is formatted correctly without constantly editing.

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.