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

pierre4854's avatar

2 relations on same table not working ?

Hi guys,

Today, I've a problem. I created 2 tables called matches and teams. My relations are defined like this :

class Match extends Model
{
    public function home_team()
    {
        return $this->belongsTo('App\Team', 'home_team');
    }
    public function away_team()
    {
        return $this->belongsTo('App\Team', 'away_team');
    }
}
class Team extends Model
{
    public function home_matches()
    {
        return $this->hasMany('App\Match', 'home_team');
    }

    public function away_matches()
    {
        return $this->hasMany('App\Match', 'away_team');
    }
}

Now, on a view, I try to display the name of the home team and the away team. In my view, I try this :

{{ $match->home_team->name }}

But I'm getting this error :

ErrorException (E_ERROR) Trying to get property 'name' of non-object (View: /Applications/MAMP/htdocs/rugbycentre/resources/views/matches/show.blade.php)

Am I missing something ? Or it's just not possible to have 2 relations on same tables ?

Thanks

0 likes
4 replies
tykus's avatar

Everything should work providing (i) the columns on matches table are called home_team_id and away_team_id and (ii) there is a valid id in each of those columns referencing the teams table

1 like
tykus's avatar
tykus
Best Answer
Level 104

Updated earlier reply - the foreign key names should be different from the name of the relationship - Laravel's Model magic __get method will match the property name first rather than the relation:

    // Match.php
    public function home_team()
    {
        return $this->belongsTo('App\Team');
    }

    public function away_team()
    {
        return $this->belongsTo('App\Team');
    }

Your schema should have home_team_id and away_team_id on the matches table.

On the other hand, if you are locked into the home_team and away_team column names, then just change the relationship names, e.g.:

    // Match.php
    public function hometeam()
    {
        return $this->belongsTo('App\Team');
    }

    public function awayteam()
    {
        return $this->belongsTo('App\Team');
    }

Then, you can use $match->hometeam->name

pierre4854's avatar

Cheers, thanks very much for your explanations very clear :smile:

Please or to participate in this conversation.