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

pierre4854's avatar

Unable to access on foreign attributes via the pivot table

Hi guys,

First, apologizes if my question has already been asked many times. I have three tables: Referees, Match and Roles. Theses tables are linked with a Many to Many relationship like this :

    public function referees()
    {
        return $this->belongsToMany('App\Referee', 'leads');
    }

And

    public function matches()
    {
        return $this->belongsToMany('App\Match', 'leads');
    }

On matches index page, I want to retrieve the list of matches with each referees and their roles for each games. I tried this :

                        @if(!$match->referees->isEmpty())
                            <ul>
                                @foreach($m->referees as $r)
                                    <li>{{ $r->first_name }} {{ $r->name }} : {{ $r->role->name}}</li>
                                @endforeach
                            </ul>
                        @else
                            -
                        @endif

But it gives me this error and I can't understand why:

Trying to get property 'name' of non-object

Could you please help me ?

0 likes
9 replies
skliche's avatar

$r->role->name

Have you defined a role relationship?

pierre4854's avatar

Yes, like this :

    public function roles()
    {
        return $this->belongsToMany('App\Role', 'leads');
    }
rin4ik's avatar

$m what this variable means in foreach loop? $match?

skliche's avatar

role is not the same as roles.

1 like
pierre4854's avatar

@rin4ik Yes, it's in a loop

@skliche Yes, it's a mistake from myself but it doesn't change my problems. Now, I'm getting this :

Property [name] does not exist on this collection

So, my table leads contains : role_id, referee_id and match_id and I just want to get the referee name and his role for each match. Is it possible or not ?

rin4ik's avatar

How did you pass $match in your controller? show pls method

rin4ik's avatar

try this code

  @if(!$match->referees->isEmpty())
 <ul>
@foreach($m->referees as $r)
    {{ $r->first_name }} {{ $r->name }} :
      @foreach($r->roles as $role)
    {{ $role->name}}
       @endforeach 
    @endforeach
</ul>
   @else
                          
@endif 
1 like

Please or to participate in this conversation.