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

Ranfty's avatar

Multiple relations

I'm trying to work out what relations to use between three tables.

Schema
lakes
    id
    name
    ...

fish
    id
    name
    ...

lake_fish
    lake_id
    fish_id
Relationships

Lake model:

class Lake extends Model
{
    /**
     * Get the fish belonging to the lake.
     */
    public function fish()
    {
        return $this->hasMany('App\LakeFish', 'lake_id');
    }
}

And the LakeFish model:

class LakeFish extends Model
{
    /**
     * Get the lake the fish belongs to.
     */
    public function lake()
    {
        return $this->belongsTo('App\Lake', 'lake_id');
    }

    /**
     * Get the fish belonging to the lake.
     */
    public function fish()
    {
        return $this->belongsTo('App\Fish', 'fish_id');
    }
}

I am wanting to output all the fish related to a lake in my view. The only way I can think of doing this is by using:

@foreach ($lake->fish as $fish)
    <p>{{ $fish->fish->name }}</p>
@endforeach

I want to be able to something like this:

@foreach ($lake->fish as $fish)
    <p>{{ $fish->name }}</p>
@endforeach

Am I missing something? Any suggestions would be grateful.

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

It is not necessary to have a Model for the LakeFish entity presuming that this is just a pivot table with foreign keys only. You only need a Lake model and a Fish model. You have not used the naming convention however, so you will ned to specify this when you are defining the relationship.

Lake.php

public function fish()
{
    return $this->belongsToMany('App\Fish', 'lake_fish');
}

Fish.php

public function lakes()
{
    return $this->belongsToMany('App\Lake', 'lake_fish');
}

Now you can fetch the fish in lake (or the lakes where a fish can be found):

@foreach ($lake->fish as $fish)
    <p>{{ $fish->name }}</p>
@endforeach 

// or if you have a fish object
@foreach ($fish->lakes as $lake)
    <p>{{ $lake->name }}</p>
@endforeach 

Personally, I would call the relationship fishes though, it's not 100% incorrect, and clarifies your code :D

Ranfty's avatar

It worked! Thanks for your help.

1 like

Please or to participate in this conversation.