Graham
Graham

Reputation: 1960

eloquent getting relationship data from relationship

Probaly this is a easy fix or i'm going about it in the wrong way but hope someone here can help me out.

I have the following models

The Event models has many exhibitor's which are related through the exhibitorExtra model.

What i'm trying to do is get for an event the exhibitor and exhibitorExtra data.

This returns the event data.

$event = Event::where('Name', $name)->firstOrFail();

The following retrieves all the extra data for an exhibitor through an hasMany relationship.

$exhibitorsExtra = $event->getExtraData->all();

This returns all the exhibitors data through a hasManyThrough function which is working.

$exhibitors = $event->exhibitors->all();

In my view I need all the data from the exhibitor for an event. So this includes the extra data. In the above way I have all the values separated. In my view i'm going to loop through all the exhibitors in which I need to echo exhibitor and exhibitor extra data. What would be the best way of doing this?

I tried to retype everything in english to make it more clear. So if I have any spelling mistake just let me know and i'll change it for other people for further use.

UPDATE

I've changed the line in the controller to the following:

$event = Event::with('exhibitors')->with('exhibitorsExtra')->where('Name', $slug)->firstOrFail();

In this way I have an Event with 2 relationships which holds the data. Now in my view I want to do something like:

@foreach ($event->exhibitors as $index => $exhibitor)
    // Here I have the exhibitor data but how do I acces the exhibitorExtra data?
@endforeach

Upvotes: 0

Views: 29

Answers (1)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

You add a HasMany relationship ExhibitorExhibitorExtra (called extra).

Change your controller:

$event = Event::with('exhibitors.extra')->where('Name', $slug)->firstOrFail();

Then you can access it in your view:

@foreach ($event->exhibitors as $index => $exhibitor)
    @foreach($exhibitor->extra as $extra)
        //
    @endforeach
@endforeach

Upvotes: 1

Related Questions