dns_nx
dns_nx

Reputation: 3943

Laravel - Eloquent relation - many-to-many - get intermediate table columns

I have a question about Laravel Eloquent Relations.

I have the following table situation:

Table guests:

Table landing_pages:

A guest can have several landing pages. And a landing page will have multiple guests. So I thought, I can use a many-to-many relationship there and I created a new table

Table guests_landing_pages:

I would be able to use this the following way: In guest Model I can do this, to create the many-to-many relationship:

public function landing_pages()
{
    return $this->belongsToMany(\App\Models\LandingPage\LandingPage::class, 'guests_landing_pages','landing_page_id','guest_id');
}

... and the other way round in landing_page model. But actually the table guests_landing_pages contains more data than just the guest_id and landing_page_id relation. There are several other fields in it:

Table guests_landing_pages:

My question is now, how can I realize this best. If I would use the many-to-many relation as described above, I will not be able to access the fields in the intermediate table, won't I? Or will the best solution to this to create a GuestLandingPages model with all the fields and create hasMany relations to/in both?

Upvotes: 1

Views: 1489

Answers (1)

Emeka Mbah
Emeka Mbah

Reputation: 17553

Laravel Eloquent has features for retrieving intermediate columns.

public function landing_pages()
{
    return $this->belongsToMany(\App\Models\LandingPage\LandingPage::class, 'guests_landing_pages','landing_page_id','guest_id')
                ->withPivot('max_persons', 'answers');
}

Upvotes: 3

Related Questions