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

mdeorue's avatar

Eager Loader Pivot Use Case

Hi guys, (first, my english is too bad) I got a use case that I been think but can resolve in a way that I like.

I have 3 tables of a soccer app...

Teams

  • id
  • description

Players

  • id
  • name

Player_Team

  • id_player
  • id_team
  • position

I need to add a new attribute "captain", so I think two ways...

  1. Put 'is_captain' (boolean) column in player_team pivot table.
  2. Put 'captain_id' foreign key in team table.

I think that the better way is the first. But when I eager load captain relation I have a Collection that only have one item (or null). So when I need to print this, I allways need to use first().

Is any way that you see that I can make a hasOne relation using the pivot table has a parameter.

This is what I got

Team model

public function captain() { return $this->belongsToMany('App\Player')->where('player_team.is_captain', true); }

AppController

$teams = Team::with('captain)->get()

Blade View

@foreach(teams as team) {{ team->captain->first()->name }} @endforeach

0 likes
0 replies

Please or to participate in this conversation.